首页 > 解决方案 > Selenium.common.exceptions.NoSuchElementException 错误,即使有显式等待

问题描述

有什么问题?

我目前正在尝试从 subreddit 中抓取数据(我正在使用 old-reddit chrome-extension,它可以恢复 reddit 的旧外观 -> 这样更容易抓取),但每当我试图获得结果时,我都会得到这段代码的错误:

xpath = "//a[@class='title may-blank loggedin ']"
element = driver.find_element_by_xpath(xpath)

selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//a[@class='title may-blank loggedin']"}

我试图解决什么问题?

我已经看到很多帖子都有类似的错误,通常与在页面加载之前抓取结果有关。我试图解决这个问题:

time.sleep(20)

但仍然没有区别。

路径也是正确的。我在 Chrome 的控制台上输入了相同的路径,它显示了正确的结果。

当我搜索标签名、类名等时,我也会得到正确的结果。

提前谢谢你的帮助!!

堆栈跟踪

Traceback (most recent call last):
  File "D:\Web_Dev\Projekte\cs50_project\test.py", line 68, in <module>
    main()
  File "D:\Web_Dev\Projekte\cs50_project\test.py", line 32, in main
    element = driver.find_element_by_xpath(xpath)
  File "C:\Users\User\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\User\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\User\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\User\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response    
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class='title may-blank loggedin ']"}
  (Session info: chrome=88.0.4324.150)

标签: pythonseleniumweb-scraping

解决方案


我会尝试在 xpath 中增加类,如下所示:

    xpath = "//a[@class='title'][@class='may-blank'][@class='loggedin']"
    element = driver.find_element_by_xpath(xpath)

或者像这样:

    xpath = "//a[@class='title' and @class='may-blank' and @class='loggedin']"
    element = driver.find_element_by_xpath(xpath)

推荐阅读