Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用try-expect跳过selenium无法使用selenium和Python定位元素的情况_Python_Selenium_Webdriver_Try Except_Nosuchelementexception - Fatal编程技术网

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

如何使用try-expect跳过selenium无法使用selenium和Python定位元素的情况,python,selenium,webdriver,try-except,nosuchelementexception,Python,Selenium,Webdriver,Try Except,Nosuchelementexception,我的问题是如何使用try-expect跳过selenium无法定位元素的情况。 由于某些原因,我不得不跳过上面描述的情况。我想使用try-expect,但除了它之外,我不知道以后要写什么 我使用Python版本3.8.6、chromeriver版本87.0.4280.88和selenium版本3.141.0,窗口10 例如(): 出现当前错误: selenium.common.exceptions.NoSuchElementException: Message: no such element:

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

我使用Python版本3.8.6、chromeriver版本87.0.4280.88和selenium版本3.141.0,窗口10

例如():

出现当前错误:

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
等等,但我不知道在上面的情况下应该写什么类型的错误

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

find_element_by_xpath() 如果找不到元素,则返回

因此,理想情况下,您需要捕获NoTouchElementException,有效的代码块将是:

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
通过xpath()查找元素 如果找不到元素,则返回

因此,理想情况下,您需要捕获NoTouchElementException,有效的代码块将是:

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

我终于知道原因了。我应该写
import selenium
,而不是
from selenium import*
,错误类型应该是
selenium.common.exceptions.NoSuchElementException
@Alen抱歉,我应该在我的回答中早些时候添加导入。我终于知道了原因。我应该写
import selenium
,而不是
from selenium import*
,错误类型应该是
selenium.common.exceptions.NoSuchElementException
@Alen抱歉,我应该在我的回答中早些时候添加导入。