简体   繁体   English

如果 selenium 无法找到元素,我如何使关闭 selenium 无效

[英]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.如果元素存在,我试图返回 false,但如果元素不存在,我不想结束程序。
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.我的问题是,当 Selenium 找不到元素时,它会关闭所有但我不想关闭它,我想运行代码的 rest。
Is it possible?可能吗?

My Python code:我的 Python 代码:

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: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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