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

Selenium无法连接chromedriver:PythonAnywhere运行异常求助

PythonAnywhere部署Selenium无法连接Chrome的解决方案

本地运行Selenium相关代码完全正常,但部署到PythonAnywhere后,无论是用SeleniumBase的Driver初始化,还是直接调用undetected_chromedriver,都会触发WebDriverException,错误提示无法连接到127.0.0.1:9222的Chrome。

核心原因

PythonAnywhere是无桌面的服务器环境,直接启用Chrome的headless模式时,缺少虚拟显示环境(Xvfb)支撑,导致Chrome无法正常启动并建立连接。你提供的可运行代码正是通过sbvirtualdisplay创建了虚拟桌面,同时关闭了headless模式,才解决了连接问题。

解决方案

1. 确保依赖安装

先确认已安装sbvirtualdisplay(用于创建虚拟显示):

pip install sbvirtualdisplay

PythonAnywhere通常预装了Xvfb(虚拟显示服务),若缺失可联系平台支持或自行安装。

2. 调整代码逻辑

所有涉及Chrome启动的代码,必须先创建虚拟显示环境,且不要启用headless=True,改为在虚拟桌面中运行正常模式。

修改尝试代码1(SeleniumBase版本)

from sbvirtualdisplay import Display
from seleniumbase import Driver

# 启动虚拟显示
display = Display(visible=0, size=(1440, 1880))
display.start()

driver = Driver(uc=True, headless=False, no_sandbox=True, disable_gpu=True, incognito=True)
try:
    driver.get('https://google.com/')
    print(f"Page title was '{driver.title}'")
finally:
    driver.quit()
    # 停止虚拟显示
    display.stop()

修改尝试代码2(undetected_chromedriver版本)

from sbvirtualdisplay import Display
import undetected_chromedriver as uc

# 启动虚拟显示
display = Display(visible=0, size=(1440, 1880))
display.start()

options = uc.ChromeOptions()
options.add_argument("--disable-extensions")
options.add_argument('--disable-application-cache')
options.add_argument('--disable-gpu')
options.add_argument("--no-sandbox")
# 注意:不要设置--headless参数
options.add_argument("--disable-setuid-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--incognito")

driver = uc.Chrome(options=options)
try:
    driver.get('https://google.com')
    print(f"Page title was '{driver.title}'")
finally:
    driver.quit()
    # 停止虚拟显示
    display.stop()

关键注意点

  • 虚拟显示是PythonAnywhere上运行Chrome的必要前提,无此环境Chrome无法在无桌面场景启动
  • 不要使用headless=True,虚拟桌面已提供隐藏显示环境,非无头模式才能正常建立连接
  • 保留no-sandbox、disable-dev-shm-usage等参数,适配服务器的安全限制与资源限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:33:24