mike 5 days ago

Python Selenium find this element OR this element

Wondering if there is a way to find the same element in 2 instances. I run into this problem where sometimes it finds the element and sometimes doesn't (Not a time issue)

Something like:

driver.find_element_by_xpath("Element xpath 1" or "Element xpath 2")

Answers


alecxe 5 days ago

One way to solve it would be to follow the EAFP approach:

from selenium.common.exceptions import NoSuchElementException

try:
    element = driver.find_element_by_xpath("Element xpath 1")
except NoSuchElementException:
    element = driver.find_element_by_xpath("Element xpath 2")

Another approach would be to modify the expression and join two xpath expressions into a single one with "or" (a pipe character):

element = driver.find_element_by_xpath("//path1/to/element | //path2/to/element")

Post Status

Asked in 5 days ago
Viewed 3,737 times
Voted 14
Answered 1 times

Search




Leave an answer