在我嵌套findelement后,元素列表继续使用第一个元素

时间:2017-06-20 21:16:04

标签: java selenium

如下所示,我获取列表中的所有行。然后,当遍历行列表时,我从每行中提取Web元素。但是当我拿出网页元素时,我会继续获取列表中的第一个网页元素。

System.out.println(row.getText()); //Prints correct values
System.out.println(actualFirstName.getText() + " " + actualLastName.getText()); //Prints incorrect values 

代码:

private WebElement getElementRow(WebDriver driver, String expectedFirstName, String expectedLastName) throws Exception{
    List<WebElement> allRows = getAllRows(driver);
    WebElement actualFirstName;
    WebElement actualLastName;
    for(int i=0; i<allRows.size(); i++){
        WebElement row = allRows.get(i);
        System.out.println(row.getText());
        actualFirstName = row.findElement(firstNameLocator);
        actualLastName = row.findElement(lastNameLocator);
        System.out.println(actualFirstName.getText() + " " + actualLastName.getText());
        if(actualFirstName.getText().equals(expectedFirstName)) && actualLastName.getText().equals(expectedLastName)){
            return row;
        }
    }
    throw new Exception(expectedFirstName + " " + expectedLastName + "  row not found in the list");
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在进一步检查我的By定位器之后,我意识到我的xpath引用了第一个元素

我有

private By brokerFirstNameLocator = By.xpath("//div[contains(@id,'first-name')]");
private By brokerLastNameLocator = By.xpath("//div[contains(@id,'last-name')]");

我本应该去哪里

private By firstNameLocator = By.xpath("./div[contains(@id,'first-name')]"); 
private By lastNameLocator = By.xpath("./div[contains(@id,'last-name')]"); 

TBH我感到惊讶,我的初始方式并没有起作用,但这是一个相对与绝对路径问题