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

时间:2020-12-12 20:55:44

I'm trying to verify page header titles on two different pages.

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

  1. Accessing the site and verifying the page header title.
  2. 访问该站点并验证页眉标题。

  3. Entering an input in text field and clicking on submit button.
  4. 在文本字段中输入输入并单击“提交”按钮。

  5. Verifying the page header title
  6. 验证页眉标题

Page from step 1 and step 3 has same xpath for header titles, when I'm trying to access and verify, I get an error message:

步骤1和步骤3中的页面具有相同的标题标题的xpath,当我尝试访问和验证时,我收到一条错误消息:

expected(expected title) but found(unexpected title)

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

Code:

/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

在此处输入图像描述

Screenshots for HTML Code :

HTML代码的屏幕截图:

1 个解决方案

#1


1  

It's probably a timing issue, the driver still reading the old header. You can use Expected Conditions to wait for the text to become what you are waiting for

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

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"));

Or wait for the first header to become stale

或者等待第一个标题变得陈旧

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

Edit

If its the same element you can use textToBePresentInElement

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

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

#1


1  

It's probably a timing issue, the driver still reading the old header. You can use Expected Conditions to wait for the text to become what you are waiting for

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

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"));

Or wait for the first header to become stale

或者等待第一个标题变得陈旧

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

Edit

If its the same element you can use textToBePresentInElement

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

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