'Getting the last element that starts-with a string (selenium)

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?



Solution 1:[1]

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)

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rudizabudi
Solution 2 dheeraj