开发者

How to manipulate user selected text using webdriver?

开发者 https://www.devze.com 2023-04-06 13:18 出处:网络
Lets say i have the following snippet in my web page: <p> This is some text </p> I want WebDriver to select \"some\" in this text, as if the user selected it. How should i do this? I know ho

Lets say i have the following snippet in my web page:

<p> This is some text </p>

I want WebDriver to select "some" in this text, as if the user selected it. How should i do this? I know how to get the <p>-element:

WebElement editable = getDriver().findElement(By.id("someId"));
editable = editable.findElement(By.tagName("p"));
System.out.println(p.getText());

The println prints "This is some text".

I tried sending keys to the element, and that used to work(in selenium 2.0b), but i'm using selenium 2.6.0 now, and it sto开发者_StackOverflow社区pped working:

editable.sendKeys(Keys.chord(Keys.SHIFT, Keys.LEFT));

Does anyone have ideas? I'm using the FirefoxDriver.


I did this once for Firefox using Javascript. Basically I used the range object in Firefox to select the text. Change the start and end range index based on what you want to select. This would not work in IE, because selecting range is conceptually different in IE. I don't have the IE code handy but since you are concerned about FF, you could give this a shot. Let me know if you interested in IE text range.

String script = "var range = document.createRange();" +
"var start = document.getElementById('idofthedivthatcontainstext');" +
"var textNode = start.getElementsByTagName('p')[0].firstChild;" +
"range.setStart(textNode, 8);" +
"range.setEnd(textNode, 13);" +
"window.getSelection().addRange(range);";
 ((JavascriptExecutor)driver).executeScript(script);


You are trying to select the contents of the p tag by drag select right I am not sure if that is objectively possible to be done by the user as your are suggesting.. Selenium now tries to mock the exact action that a user can perform on a browser. thus you just cant send a shift and left select key on the p tag and expect it to select unlike a textbox where it is very much possible but you might probably have to click on the text box first to get it into focus.

Here is what I would suggest to achieve this, not sure if it will work.

a) send the left click on the p tag
b) hold the shift key
c) drag the mouse to the end of the p tag.

Hope that helps.


Use the .Text property of the IWebElement

WebElement editable = getDriver().findElement(By.id("someId"));
editable = editable.findElement(By.tagName("p").Text).ToString();
editable.Replace("This is ", "").Replace(" text.");
System.out.println(p.getText());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号