我有一个非常简单的代码,我在其中寻找一个类,当该类不存在时,我想捕获该类并更新CSV中的状态。我正在这样实现:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time
invalid = browser.find_element_by_class_name('_3lLzD')
try:
Update status
except NoSuchElementException as e:
Update Status
它仍然引发错误:
Traceback (most recent call last):
File "C:/Users/Krenovate/Desktop/automate/automate/automate.py", line 35, in <module>
invalid = browser.find_element_by_class_name('_3lLzD')
File "C:\Users\Krenovate\PycharmProjects\mxrecord\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
return self.find_element(by=By.CLASS_NAME, value=name)
File "C:\Users\Krenovate\PycharmProjects\mxrecord\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Users\Krenovate\PycharmProjects\mxrecord\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\Krenovate\PycharmProjects\mxrecord\venv\lib\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: ._3lLzD
我在做什么错了
答案 0 :(得分:1)
对于documentation,定位器函数旨在引发未找到的异常。因此,您得到的异常完全符合预期的行为。
如果不确定元素的存在,最简单的方法是将其放在try块中
try:
invalid = browser.find_element_by_class_name('_3lLzD')
Update status
except NoSuchElementException as e:
Update Status
或使用explicit waits超时。