两个不同页面上的两个元素的相同XPath。如何使用Java中的Selenium WebDriver访问它们?

时间:2017-06-19 11:33:58

标签: java selenium xpath webdriver

我试图在两个不同的页面上验证页眉标题。

  1. 访问网站并验证页眉标题。
  2. 在文本字段中输入输入,然后单击“提交”按钮。
  3. 验证页眉标题
  4. 第1步和第3步的网页标题标题相同xpath,当我尝试访问和验证时,收到错误消息:

      

    预期(预期标题)但发现(意外标题)

    代码:

    /html/body/div[4]/div/div[1]/div/h1/span
    /html/body/div[4]/div/div[1]/div/h1/span
    

    enter image description here

    enter image description here

    HTML代码的屏幕截图:

1 个答案:

答案 0 :(得分:1)

这可能是一个时间问题,驱动程序仍在阅读旧标题。您可以使用Expected Conditions等待文本成为您正在等待的内容

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement header = wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("/html/body/div[4]/div/div[1]/div/h1/span"), "expected title"));

或等待第一个标题变为陈旧

WebElement firstHeader = driver.findElement(...);
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.stalenessOf(firstHeader));
WebElement secondHeader = driver.findElement(...);
  

修改

如果它是相同的元素,您可以使用textToBePresentInElement

WebElement header = driver.findElement(...);
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.textToBePresentInElement(header, "expected title"));