Selenium 没有直接处理文本节点的 API。
但是,您可以使用一段 JavaScript 检索单词位置,并通过提供相对于包含文本的元素的偏移位置,使用 Actions 类单击前一个单词。
这是一个双击“Exchange”前面的单词“Stack”的例子:
// script to get the relative position/size of a word in an element
final String JS_GET_WORD_RECT =
"var ele=arguments[0], word=arguments[1], rg=document.createRange(); " +
"for(var c=ele.firstChild, i; c; c=c.nextSibling){ " +
" if(c.nodeType != 3 || (i=c.nodeValue.indexOf(word)) < 0) continue; " +
" rg.setStart(c, i); rg.setEnd(c, i + word.length); " +
" var r = ele.getBoundingClientRect(), rr = rg.getClientRects()[0]; " +
" return { left: (rr.left-r.left) | 0, top: (rr.top-r.top) | 0, " +
" width: rr.width | 0, height: rr.height | 0 }; " +
"};";
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
// load the page
driver.get("http://stackexchange.com/legal/content-policy");
// get the text element
WebElement element = driver.findElement(By.cssSelector(".sectionheader > h2:nth-child(1)"));
// get the relative position/size {left, top, width, height} for the word "Exchange"
Map rect = (Map)js.executeScript(JS_GET_WORD_RECT, element, "Exchange");
// define a relative ckick point for the previous word "Stack"
Long offset_x = (long)rect.get("left") - (long)rect.get("width") / 2;
Long offset_y = (long)rect.get("top") + (long)rect.get("height") / 2;
// double click the word "Stack"
new Actions(driver)
.moveToElement(element, offset_x.intValue(), offset_y.intValue())
.doubleClick()
.perform();
driver.quit();