Python中Selenium无头模式使用报错求助:官方代码仍无法运行
解决Chrome无头模式TimeoutException的方案
排查与修复步骤
手动指定Chrome二进制路径:无头模式下有时无法自动定位Chrome安装位置,手动指定可避免启动异常:
from selenium import webdriver from selenium.webdriver.chrome.service import Service options = webdriver.ChromeOptions() options.add_argument("--headless=new") # 替换为你的Chrome实际安装路径,Windows常见路径示例如下 options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe" service = Service(r"C:\Program Files (x86)\WebDrivers\chromedriver.exe") driver = webdriver.Chrome(service=service, options=options)补充模拟正常浏览器的参数:无头模式默认环境与普通浏览器差异较大,添加以下参数可降低被拦截或加载异常的概率:
options.add_argument("--window-size=1920,1080") # 设置窗口尺寸,避免布局异常 options.add_argument("--disable-gpu") options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") options.add_argument("--enable-javascript")延长超时时间阈值:无头模式下页面加载速度可能更慢,显式设置更长的超时时间:
driver.set_page_load_timeout(60) # 页面加载超时设为60秒 driver.implicitly_wait(30) # 元素查找隐式等待30秒校验ChromeDriver与Chrome版本匹配:Selenium 4.18.0要求ChromeDriver与本地Chrome版本严格对应(通常支持Chrome 119-121版本),可通过
chrome://version/查看Chrome版本,确保ChromeDriver版本一致。禁用扩展与弹窗拦截:无头模式下残留的浏览器扩展可能干扰运行,添加参数禁用:
options.add_argument("--disable-extensions") options.add_argument("--disable-popup-blocking")
验证方式
先尝试访问简单页面(如driver.get("https://www.google.com")),确认无头模式可正常启动后,再切换到目标页面,逐步排查是否为目标网站反爬机制导致超时。
内容的提问来源于stack exchange,提问作者PiglerBigler
相关产品推荐
相关产品推荐

