Home > Mobile >  Getting the last element that starts-with a string (selenium)
Getting the last element that starts-with a string (selenium)

Time:03-21

I'm getting some info from this page, and I'm trying to identify the last element that starts with the string "about". In other words, trying to get : "About the Runaway Grooms". I'm trying this code:

try:
    BioHeader= driver.find_element_by_xpath("//div[starts-with(text(),'About')][last()]")
    print("Bio header: ", BioHeader.text)
except (ElementNotVisibleException, NoSuchElementException, TimeoutException):
    pass

But it's giving me the first, not last instance. What am I doing wrong here?

CodePudding user response:

driver.find_element_by_xpath gives you just one element, the first one.

You need this, which generates a list of all instances.

from selenium.webdriver.common.by import By
BioHeader = driver.find_elements(By.XPATH, "//div[starts-with(text(),'About')][last()]")
print("Bio header: ", BioHeader[1].text)

CodePudding user response:

Probably locator to be defined as below, can you please try as below

try:
    BioHeader= driver.find_element_by_xpath("(//div[starts-with(text(),'About')])[last()]")
    print("Bio header: ", BioHeader.text)
except (ElementNotVisibleException, NoSuchElementException, TimeoutException):
    pass
  • Related