簡體   English   中英

Selenium.common.exceptions.NoSuchElementException 錯誤,即使顯式等待

[英]Selenium.common.exceptions.NoSuchElementException error even with explicit waiting

有什么問題?

我目前正在嘗試從 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 的控制台上輸入了相同的路徑,它顯示了正確的結果。

當我搜索標簽名稱、class 名稱等時,我也得到了正確的結果。

提前謝謝你的幫助!!

堆棧跟蹤

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)

我會嘗試在 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)

發生了什么?

Calling this XPath "//a[@class='title may-blank loggedin ']" does not work for Selenium because the space is like a delimiter for classes in HTML so you are looking for a class which cant exsist.

如何解決?

解決這個問題非常簡單,只需放置點而不是分隔符,以表明您正在尋找一個具有所有三個類的元素,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM