【发布时间】:2019-10-17 00:46:52
【问题描述】:
我正在使用带有 selenium web 驱动程序的自动化脚本。它通常可以正常工作,但有时页面上的内容会发生变化。
如果它正在寻找的元素不存在,则它正在崩溃而不是执行 else 语句。
我尝试通过 try 和 NoSuchElementException 使用另一个函数,但我确实收到了另一个关于 NoSuchElementException 的错误。
这是 if else 语句:
#Look for link text "Stores"
find_store = driver.find_element_by_link_text('Stores')
if find_store:
find_store.click()
else:
driver.get("https://example.com/myaccount")
time.sleep(5)
这是 try 语句:
try:
find_store = driver.find_element_by_link_text('Stores')
if find_store.is_displayed():
find_store.click() # this will click the element if it is there
print("Store found, all good.")
except NoSuchElementException:
driver.get("https://example.com/myaccount")
print("Store was not found, visiting base URL to search for store")
time.slep(5)
在第一个脚本中,我希望它搜索元素。如果它不存在,则访问 URL,以便我可以在那里搜索元素。但它永远不会打开 URL,我收到此错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:
我希望在第二个脚本中寻找元素。如果该元素不存在,它应该访问基本 url 并稍后在代码中重试。但是在这里我得到了这个错误:
except NoSuchElementException:
NameError: name 'NoSuchElementException' is not defined
我想了解如何避免脚本崩溃并在元素不存在时实际执行替代操作。谢谢。
【问题讨论】:
-
NoSuchElementException不是全局定义的名称。您必须先导入它才能使用它:from selenium.common.exceptions import NoSuchElementException也许。