Selenium使用鼠标悬停处理不同元素的相同链接文本

时间:2016-03-10 16:35:43

标签: java internet-explorer selenium selenium-webdriver

受测试系统有三个级别的鼠标悬停:I级II级 - 级别III。一旦我们将鼠标移到第一级,就可以看到第二级。同样将鼠标悬停至Level II以查看Level III 问题:在某些情况下,Level II链接文本与Level III相同。在这些情况下,我的代码选择了Level II链接文本而不是Level III,因为两个链接文本都是可见的,而selenium选择它在DOM中找到的第一个。 假设:I级链接文本是:A 二级链接文本选项:B | C | D | III级选项:X | Y | B

我想知道在这种情况下如何处理linktext B,因为它总是从Level II而不是Level III中选择B.

以下是我的代码:

public boolean mouseOver(String levelI, String levelII, String levelIII) throws InterruptedException {
     try {
    waits.until(ExpectedConditions.titleContains("abc"));
     } catch (NoSuchElementException e) { 
     }
    boolean result = false;
    int attempts = 0;
    while (attempts < 3) {

    try {
    Actions action = new Actions(driver);
    WebElement selectAnEquipment = driver.findElement(By.linkText(levelI));
    action.moveToElement(selectAnEquipment).perform();
    WebElement mouselevelII = driver.findElement(By.linkText(levelII));
    action.moveToElement(mouselevelII).perform();           
    WebElement mouselevelIII = driver.findElement(By.linkText(levelIII));
    action.moveToElement(mouselevelIII).click().build().perform();
    result =true;
    break;
    } catch (NoSuchElementException e) {    
    }
        attempts++;
    }
    return result;
} 

1 个答案:

答案 0 :(得分:0)

如果它不是非常动态,你可以通过xpath找到一个元素:

//find first element with link text = levelII
driver.findElement(By.xpath("(//a[contains(text(),'" + levelII + "')])[1]"));
//find second element with link text = levelIII
driver.findElement(By.xpath("(//a[contains(text(),'" + levelIII + "')])[2]"));

但如果你不知道levelII何时等于levelIII,那么我会做这样的事情:

List<WebElement> list1 = driver.findElements(By.linkText(levelI));
List<WebElement> list2 = driver.findElements(By.linkText(levelII));
List<WebElement> list3 = driver.findElements(By.linkText(levelIII));

//now you can handle on it like
//if levelII == levelIII
if (list2.size() == 2 && list3.size() == 2) {
    //mouse over first founded element with link text = levelII = levelIII
    action.moveToElement(list2.get(0)).perform();
    //mouse over second founded element with link text = levelII = levelIII
    action.moveToElement(list3.get(1)).click().build().perform();
}
else {
    //the default handling in your code above
}

我希望它有所帮助...