How to Verify the Existence of Elements in XPath

Asked 2 years ago, Updated 2 years ago, 111 views

python 2.7.10 and selenium and chrome driver.

When using selenium in python and finding_element using xpath, I would like to separate the processing according to whether or not the xpath element exists. How should I describe it?

driver.find_element(By.XPATH, '//*[@id="rank"]/tbody/tr[2]/td[1]').text

I'd like to branch with an if statement, but I got an error saying, "There's no such element in the if statement!"

If anyone knows, please let me know.

python selenium

2022-09-30 21:19

2 Answers

Use find_elements.The return type is a list, and if there is no corresponding element, it will only be an empty list.


2022-09-30 21:19

Python handles exceptions with try and except.
Write conditional expressions and functions using ":" and indentation.

try:
    # What to do if there is an element?
    driver.find_element(By.XPATH, '//*[@id="rank"]/tbody/tr[2]/td[1]').text
except:
    # What to do if there is no element (*To be exact, if an error occurs by executing the contents of try)
    Described here


2022-09-30 21:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.