如果元素不存在,我试图返回false,但是如果元素不存在,我不想结束程序。我的问题是,当Selenium找不到元素时,它会关闭所有元素,但我不想关闭它,我想运行其余的代码。可能吗?
我的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()
输出:
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']"}
您可以捕获异常。
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
解决了我的NoSuchElementException以外的问题。您必须添加from selenium.common.exceptions import NoSuchElementException
我的Python代码:
try:
if driver.find_element_by_xpath("//a[@class='btn btn-primary im_edit_forward_btn disabled']") != 0 :
print("0 new messages")
return False
except NoSuchElementException:
print("New messages found")
encaminhar = driver.find_element_by_xpath("//a[@class='btn btn-primary im_edit_forward_btn']")
encaminhar.click()