Python 按名称循环查找元素

Python 按名称循环查找元素,python,selenium,if-statement,Python,Selenium,If Statement,我有一个代码,它在其中查找一个名称,我试图编写一个if语句,表示如果找不到该名称,请查找其他名称 到目前为止,我掌握的情况如下: excel = driver.find_element_by_name("Export to Excel") if excel == None: driver.implicitly_wait(15) search = driver.find_element_by_xpath("//spa

我有一个代码,它在其中查找一个名称,我试图编写一个if语句,表示如果找不到该名称,请查找其他名称

到目前为止,我掌握的情况如下:

        excel = driver.find_element_by_name("Export to Excel")

        if excel == None:
            driver.implicitly_wait(15)
            search = driver.find_element_by_xpath("//span[@id='inplaceSearchDiv_WPQ2_lsimgspan']")
            search.click()

        else:
            excel.click()

我知道if语句中的内容是什么,因为我已经测试过了。是否允许我在if语句中更改我的论点?我得到的错误是
selenium.common.exceptions.NoSuchElementException:Message:No-this-element
我尝试输入“No-this-element”而不是“None”,但仍然得到相同的错误。它还告诉我
异常未处理的NoSuchElementException('No-this-element',None,None)
一些人能告诉我if语句的错误吗?该错误还表示它位于
excel=driver.find\u element\u by\u name(“Export to excel”)
当按钮不在页面中时。当它是时,它将直接转到语句的else部分

如果驱动程序上的find_element_by_name方法找不到webelement,它将引发NoSuchElementException异常

试试这个

from selenium.common.exceptions import NoSuchElementException

try:
    excel = driver.find_element_by_name("Export to Excel")
    excel.click()
except NoSuchElementException:
    driver.implicitly_wait(15)
    search = driver.find_element_by_xpath("//span[@id='inplaceSearchDiv_WPQ2_lsimgspan']")
    search.click()

我尝试了一下,得到了一个错误,上面写着
除了NoSuchElementException:NameError:name'NoSuchElementException'没有定义
从selenium.common.exceptions导入导入语句导入NoSuchElementException