如何使用try-except来跳过selenium无法使用Selenium和Python定位元素的情况

问题描述 投票:0回答:1

我的问题是如何使用 try-expect 来跳过 selenium 无法定位元素的情况。 由于某些原因,我不得不跳过上面描述的情况。我想使用try-expect,但我不知道 except 后面该写什么。

我使用Python版本3.8.6,chromeriver版本87.0.4280.88,selenium版本号3.141.0,window 10

例如():

driver = webdriver.Chrome()
driver.get("https:www.google.com")
try:
    driver.find_element_by_xpath('//*[@id="cdNav"]/ul/li[5]/ul/li[1]/a').click()
except:
    pass

当前发生的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[3]/div/nav/ul/li[5]/a"}
  (Session info: chrome=87.0.4280.88)

通常情况下,我可以写

IndentationError
SyntaxError
等等,但我不知道在上述情况下的EXPECT之后要写什么类型的错误。

这个问题困扰我很久了,希望能解决,非常感谢

python selenium-webdriver webdriver try-except nosuchelementexception
1个回答
1
投票

通过 xpath 查找元素

如果未找到该元素,则

find_element_by_xpath()
返回NoSuchElementException

所以理想情况下你需要捕获 NoSuchElementException 并且你的有效代码块将是:

driver = webdriver.Chrome()
driver.get("https:www.google.com")
try:
    driver.find_element_by_xpath('//*[@id="cdNav"]/ul/li[5]/ul/li[1]/a').click()
except nosuchelementexception:
    pass

注意:您必须添加以下导入:

from selenium.common.exceptions import NoSuchElementException
© www.soinside.com 2019 - 2024. All rights reserved.