python selenium webdriver中的IF-ELSE语句在元素不存在时不执行ELSE

python selenium webdriver中的IF-ELSE语句在元素不存在时不执行ELSE,python,selenium-webdriver,Python,Selenium Webdriver,我正在使用SeleniumWeb驱动程序的自动化脚本。它通常工作正常,但有时页面上的内容会发生变化 如果它要查找的元素不在那里,它将崩溃,而不是执行else语句 我尝试使用另一个函数try和NoSuchElementException,但我确实得到了另一个关于NoSuchElementException的错误 这是if-else语句: #Look for link text "Stores" find_store = driver.find_element_by_link_text('Store

我正在使用SeleniumWeb驱动程序的自动化脚本。它通常工作正常,但有时页面上的内容会发生变化

如果它要查找的元素不在那里,它将崩溃,而不是执行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:
    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)
这是try语句:

#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:
    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:
  except NoSuchElementException:
NameError: name 'NoSuchElementException' is not defined
在第二个脚本中,我希望查找元素。如果元素不在那里,它应该访问基本url,然后在代码中稍后重试。然而,在这里我得到了这个错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:
  except NoSuchElementException:
NameError: name 'NoSuchElementException' is not defined

我想学习如何避免脚本崩溃,并在元素不存在的情况下实际执行替代操作。谢谢。

使用以下命令:

if len(driver.find_elements_by_link_text('Stores'))> 0:
    driver.find_element_by_link_text('Stores').click()
else:
    driver.get("https://example.com/myaccount")
time.sleep(5)

NoTouchElementException
不是全局定义的名称。您必须先导入它,然后才能使用它:
from selenium.common.exceptions导入NoSuchElementException