简体   繁体   中英

How do I void closing selenium if selenium is unable to find an element

I am trying to return false if an element exist, but I don't want to end the program if the element doesn't exist.
My problem is that when Selenium doesn't find the element, it closes all but I don't want to close it, I want to run the rest of the code.
Is it possible?

My Python code:

if driver.find_element_by_xpath("//a[@class='btn btn-primary im_edit_forward_btn disabled']") != 0 :     
    print("Break here")
    return False

print("Running the rest")
encaminhar = driver.find_element_by_xpath("//a[@class='btn btn-primary im_edit_forward_btn']")
encaminhar.click()

Output:

Traceback (most recent call last):
  File "webscraping.py", line 94, in <module>
    if forwardMessages():
  File "webscraping.py", line 57, in forwardMessages
    if driver.find_element_by_xpath("//a[@class='btn btn-primary im_edit_forward_btn disabled']") != 0 :
  File "C:\Users\gusta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\gusta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\gusta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\gusta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class='btn btn-primary im_edit_forward_btn disabled']"}

You can catch the exception.

from selenium.common.exception import NoSuchElementException

try:
    driver.find_element_by_xpath("//a[@class='btn btn-primary im_edit_forward_btn disabled']")
except NoSuchElementException:
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM