[英]How do I void closing selenium if selenium is unable to find an element
如果元素存在,我試圖返回 false,但如果元素不存在,我不想結束程序。
我的問題是,當 Selenium 找不到元素時,它會關閉所有但我不想關閉它,我想運行代碼的 rest。
可能嗎?
我的 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:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.