Chick if object exists. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Chick if object exists. (/thread-21586.html) |
Chick if object exists. - Martinelli - Oct-05-2019 Hi, everybody! I did a robot that run procedures on a website. But, I face 04 page configurations, as follow: nav.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[1]/div/div[2]/div/div/span[1]/p[1]') nav.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[1]/div/div[2]/div/div/span[1]/p[2]') nav.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[1]/div/div[2]/div/div/span[1]/p') nav.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[1]/div/div[2]/div/div/span[1]')It happens because I get into many pages, and the text that I need to check are sometimes in one of those 04 cases. In this way, I declared all of them. But, I got the error below, because it get into in a page and the second XPATH simply does not exists. But, the program closes and do not run. So, does anyone know how can I check if that object exists before try to use it? Thanks! The error message is that: Traceback (most recent call last): File "/home/martinelli/PycharmProjects/ESAB/Zeca.py", line 50, in <module> nav.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[1]/div/div[2]/div/div/span[1]/p[2]') File "/home/martinelli/PycharmProjects/RoboTRF2/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "/home/martinelli/PycharmProjects/RoboTRF2/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element 'value': value})['value'] File "/home/martinelli/PycharmProjects/RoboTRF2/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/home/martinelli/PycharmProjects/RoboTRF2/venv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div[1]/div/div[3]/div[1]/div/div[2]/div/div/span[1]/p[2] Process finished with exit code 1 RE: Chick if object exists. - scidam - Oct-06-2019 (Oct-05-2019, 07:27 PM)Martinelli Wrote: So, does anyone know how can I check if that object exists before try to use it?You can wrap your code into try/except clause, e.g. from selenium.common.exceptions import NoSuchElementException # ... try: nav.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[1]/div/div[2]/div/div/span[1]/p[1]') except NoSuchElementException: pass # or do something RE: Chick if object exists. - Martinelli - Oct-06-2019 Thanks!! It solved the problem!! Great!! |