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

本地Selenium脚本正常,如何在PythonAnywhere更新Chrome与ChromeDriver?

在PythonAnywhere更新Chrome与ChromeDriver并解决Headless运行问题

一、先修正ChromeOptions配置错误

你当前配置里的--414,900参数格式无效,需改为--window-size=414,900,这个格式错误可能是导致网站无法正常响应的原因之一。

二、更新Chrome(仅PythonAnywhere付费用户可用)

免费用户无法使用sudo命令安装自定义软件,只能使用系统默认提供的Chrome版本;付费用户可通过以下步骤安装最新版Chrome:

  1. 打开PythonAnywhere的Bash控制台
  2. 执行以下命令:
    # 下载最新稳定版Chrome安装包
    wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
    # 安装包
    sudo dpkg -i google-chrome-stable_current_amd64.deb
    # 修复依赖缺失问题
    sudo apt-get install -f
    # 验证安装版本
    google-chrome --version
    

三、更新ChromeDriver(需与Chrome版本严格匹配)

  1. 在Bash控制台提取Chrome版本的前三位核心版本号(比如120.0.6099):
    CHROME_VERSION=$(google-chrome --version | cut -d ' ' -f 3 | cut -d '.' -f 1-3)
    
  2. 下载对应版本的ChromeDriver:
    wget https://chromedriver.storage.googleapis.com/$CHROME_VERSION/chromedriver_linux64.zip
    
  3. 解压并配置可执行权限:
    unzip chromedriver_linux64.zip
    chmod +x chromedriver
    
  4. 将ChromeDriver移动到系统PATH可识别的目录(~/.local/bin/默认在PythonAnywhere的PATH中):
    mv chromedriver ~/.local/bin/
    
  5. 验证ChromeDriver版本:
    chromedriver --version
    

四、调整脚本适配PythonAnywhere环境

针对Selenium 4.7.2版本,建议显式指定ChromeDriver路径,同时修正配置参数:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--disable-gpu")
# 可替换为Linux环境的用户代理,降低被网站识别为异常环境的概率
chrome_options.add_argument("user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.109 Safari/537.36")
chrome_options.add_argument('--lang=pt_BR')
chrome_options.add_argument('--window-size=414,900')

# 替换为你的PythonAnywhere用户名,或省略该参数(系统会自动识别~/.local/bin/下的chromedriver)
service = Service(executable_path='/home/你的用户名/.local/bin/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)

五、验证运行

执行脚本前,先在Bash控制台确认Chrome和ChromeDriver版本完全匹配,避免版本不兼容导致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:40:29