Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium webdriver getting element after page changes

Very simple question, basically I'm trying to get the text of a li element after clicking on another link. The link will cause the li orders to change. Whenever I try to get the text, it will return the text before the order changes. How do I get the li text after the order has changed from clicking a link? the link doesn't reload the page itself.

Here's what I'm using to get the element:

driver.findElement(By.cssSelector("li[id^='coupon_']:nth-of-type(1) p.brand")).getText();

The change itself will be from:

<div id="id1">
  <ul class="pods">
    <li rel="" title="some text" id="coupon_1" data-pos="1">
      ...
      <p class="brand">brand1</p>
      ...
    </li>
  </ul>
</div>

to:

<div id="id1">
  <ul class="pods">
    <li rel="" title="some text" id="coupon_5" data-pos="1">
      ...
      <p class="brand">brand5</p>
      ...
    </li>
  </ul>
</div>

I had similar situations where I would use wait.until for the element that changes to appear and then get it but in this case the li element is already present, but just changes after clicking on the link. How can I get the new element text? thanks!

like image 778
wjtest Avatar asked May 18 '26 19:05

wjtest


1 Answers

You can wait for the id change in the li

WebDriverWait wait = new WebDriverWait(driver, 10);
// wait for the new li to appear
WebElement li = wait.until(ExpectedConditions.elementToBeClickable(By.id("coupon_5")));
System.out.println(li.findElement(By.cssSelector("p.brand")).getText().trim());

or if there are multiple possibilities for the new id then you can wait for the old id element to become stale.

// get the original li that will be changed
WebElement oldLi = driver.findElement(By.id("coupon_1"));
WebDriverWait wait = new WebDriverWait(driver, 10);
// wait for the original li to go stale... change
wait.until(ExpectedConditions.stalenessOf(oldLi));
// grab the new element by whatever the new id is
WebElement newLi = driver.findElement(By.id("coupon_5"));
System.out.println(newLi.findElement(By.cssSelector("p.brand")).getText().trim());
like image 59
JeffC Avatar answered May 21 '26 09:05

JeffC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!