簡體   English   中英

TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: 消息:

[英]TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:

我使用此行代碼等待 product_id 出現,我的代碼運行良好約 30 分鍾

    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, product_id)))

然后,我收到一個錯誤

TimeoutException(message, screen, stacktrace)selenium.common.exceptions.TimeoutException: Message: 

我嘗試將 WebDriverWait 更改為 100,但我仍然無法解決它們。 我想了解為什么會出現此錯誤以及針對這種情況的任何解決方案。 非常感謝 !!!

這是我的解決方案,但我想知道此錯誤的原因並尋找更好的解決方案

  while True:
    driver.get(URL)
    try:
        element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, product_id)))
        break
    except TimeoutException:
        driver.quit()

你能提供HTML示例嗎? 沒有 HTML 示例,幾乎不可能為您調試。 代碼和 HTML 示例會有所幫助。

我的猜測是您的網站使用動態 id 定位器,或使用 iframe,或者在您的腳本中,硒在其他選項卡/窗口/iframe/內容上處於活動狀態。 這是假設您的product_id是正確的。


更新示例:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

PRODUCT_ID = 'productTitle'

driver = webdriver.Chrome()
driver.get("https://www.amazon.com/dp/B08BB9RWXD")
try:
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, PRODUCT_ID)))
    print(element.text)
except TimeoutException:
    print("Cannot find product title.")

driver.quit()

使用上面的代碼我沒有任何問題。 你可以自己擴展它:)。

您需要注意的一件事是不要使用while & break WebDriverWait(driver, 10)已經循環查找元素 10 秒。 在這 10 秒內,如果它找到您的元素,它將停止查找( break )。 您不需要自己執行while循環。

暫無
暫無

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

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