You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+Selenium无头模式页面加载超时问题求助

解决Selenium无头模式加载超时的问题

针对你遇到的无头模式超时、正常模式正常的情况,可通过以下几个方向调整配置解决:

  • 模拟常规浏览器的标识与窗口
    无头模式默认的用户代理(UA)和窗口尺寸容易被网站识别为自动化工具,导致页面渲染逻辑不同。需添加以下参数:

    • 设置符合真实浏览器的UA(可从本地Chrome的chrome://version/页面复制)
    • 指定合理的窗口大小,避免因布局压缩导致元素无法正常加载
  • 规避自动化检测机制
    多数网站会检测Selenium的特征(如webdriver属性),需禁用相关标识:

    • 关闭自动化控制特征
    • 排除自动化启动开关
    • 禁用自动化扩展
  • 优化等待策略
    仅等待元素存在可能不够,建议改为等待元素可见,或先等待页面完全加载完成。

修改后的完整代码

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

chrome_options = Options()
chrome_options.add_argument("--headless=new")
# 模拟常规浏览器UA(替换为你本地Chrome的UA)
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
# 指定窗口大小
chrome_options.add_argument("--window-size=1920,1080")
# 规避自动化检测
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
# 可选:启用图片加载(部分网站依赖图片渲染元素)
chrome_options.add_argument("--blink-settings=imagesEnabled=true")

driver = webdriver.Chrome(options=chrome_options)
# 进一步规避检测:移除navigator.webdriver属性
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

driver.get('https://www.chabad.org/calendar/zmanim_cdo/aid/143790/locationid/790/locationtype/1/save/1/tdate/4-15-2024/jewish/Zmanim-Halachic-Times.htm')
try:
    # 先等待页面完全加载
    WebDriverWait(driver, 20).until(lambda d: d.execute_script('return document.readyState') == 'complete')
    # 等待元素可见而非仅存在
    myElem = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, 'group_4/15/2024')))
    print("Page is ready!")
except TimeoutException:
    print("Loading took too much time!")
finally:
    driver.quit()

额外说明

  • 请确保Chrome浏览器与ChromeDriver版本严格匹配,版本不兼容也可能导致加载异常
  • 如果仍超时,可尝试添加--no-sandbox和--disable-dev-shm-usage参数,适配服务器环境的沙箱限制

内容的提问来源于stack exchange,提问作者Ishayahu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 01:30:00