【问题标题】:Getting tImeout error when I am using python selenium headless当我使用 python selenium headless 时出现超时错误
【发布时间】:2020-09-05 11:54:39
【问题描述】:

如果不使用 selenium 无头,以下代码可以正常工作。 但是为什么我在使用无头模式时会出错。 这是我的代码:-

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
import time


options = Options()
options.add_argument("--disable-notifications")
options.headless = True
options.add_argument("--window-size=1920,1080")
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options)

url = "https://www.justdial.com/Delhi/S-K-Premium-Par-Hari-Nagar/011PXX11-XX11-131128122154-B8G6_BZDET"
driver.get(url)


pop_up = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable((By.XPATH, '//*[@id="best_deal_detail_div"]/section/span')))
time.sleep(2.5)
pop_up.click()  # For disable pop-up



while True:
     try:
       element = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, "//span[text()='Load More Reviews..']")))
       element.click()

    except TimeoutException:
       break
    except:
       pass


print([span.text for span in driver.find_elements_by_css_selector('span.rName.lng_commn')])

请提供一些建议或解决方案。谢谢。

【问题讨论】:

标签: python python-3.x selenium selenium-webdriver web-scraping


【解决方案1】:

错误的根本原因很清楚。这是由于脚本无法找到由explicit-wait 持有的元素而导致的。

鉴于您尝试了 cmets 中提到的答案,那么这也可能与 non-headless 和 headless 模式下的异常行为问题有关。在某些情况下,无头模式无法通过 id 检测元素,在这种情况下,会传入 DOM 的完整 absolute-path。

例如下面传full xpath,看看能不能解决问题。

element = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, <full xpath>)))
       element.click()

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多