首页 > 解决方案 > Selenium NoSuchElementException:没有这样的元素:无法找到元素

问题描述

我正在尝试使用 python 进行 Web 自动化的以下代码:

from selenium import webdriver
import time

web = webdriver.Chrome()
base_url = ""
web.get(base_url)
time.sleep(2)
team = web.find_element_by_xpath('// * [@id = "ReportViewerControl_xyz123_xyz456_dvalue"]/option[4]')
team.click()

但是,我收到以下异常:

NoSuchElementException: no such element: Unable to locate element

标签: pythonseleniumwebdriver

解决方案


在开始使用之前,您需要先了解一些 HTML Selenium。你得到NoSuchElementException是因为没有找到该元素。您可以使用此导入来捕获此错误:

from selenium.common.exceptions import NoSuchElementException

然后像这样写一个try/except块:

try:
  # your code
except NoSuchElementException:
  # this block of code will execute when you get this exception

推荐阅读