使用Selenium

时间:2016-04-06 04:33:33

标签: javascript html selenium xpath

我们正在使用Selenium Webdriver进行测试自动化。这是我的要求。

HTML看起来像这样。

<p> I need to click before this. Help me achieve this </p>

&#34; p&#34;标签可以有任意数量的行。我得到一个特定的单词作为测试输入,需要将光标放在该单词之前。

我尝试使用Xpath包含文本定位元素,它返回整个段落并在段落中间点击(对于chrome)。

有人可以帮助我如何实现这个目标吗?

3 个答案:

答案 0 :(得分:0)

在JavaScript中,您可以使用document.elementFromPoint

指定坐标
document.elementFromPoint(x, y).click();

在C#和Java中,您可以使用Actions class

WebElement element = driver.findElement(By...);
Actions actions = new Actions(driver);
actions.moveToElement(element).moveByOffset(dx, dy).click().perform();

答案 1 :(得分:0)

使用getSize函数然后划分元素的高度和宽度,之后应用Action类的click方法,这里是示例代码:

   WebElement el = driver.findElement(By.xpath("//xpath"));
    Dimension location = el.getSize();
    int y = location.height/2;
    int x = location.width/2;
    Actions build = new Actions(driver);
    build.moveToElement(el, x, y).click().build().perform();

希望这会有效!!

答案 2 :(得分:0)

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();
相关问题