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

能否在PythonAnywhere安装ChromeDriver并运行本地可用的非无头模式Selenium代码?

Selenium+BeautifulSoup部署到PythonAnywhere的问题解答

本地运行代码

from selenium import webdriver
from bs4 import BeautifulSoup
import time

# Initialize webdriver
driver = webdriver.Chrome(executable_path="/Users/matteo/Downloads/chromedriver")

# Navigate to website
driver.get("https://apnews.com/article/prince-harry-book-meghan-royals-4141be64bcd1521d1d5cf0f9b65e20b5")

time.sleep(5)
# Parse page source
soup = BeautifulSoup(driver.page_source, "html.parser")

# Find desired elements using Beautiful Soup
elements = soup.find_all("p")

# Print element text
for element in elements:
    print(element.text)

# Close webdriver
driver.quit()

问题与解答

  1. 是否可在PythonAnywhere安装ChromeDriver且不使用无头模式?
  • 不行。PythonAnywhere的服务器是无GUI环境,没有显示设备支持非无头模式的Chrome运行,必须启用无头模式才能正常使用ChromeDriver。
  1. 运行该代码需安装Chrome还是Chromium即可?
  • PythonAnywhere默认预装了Chromium,不需要额外安装Chrome,直接配置ChromeDriver适配预装的Chromium版本即可。
  1. 本地运行时会打开Chrome页面,在PythonAnywhere运行是否会崩溃?
  • 直接按原代码运行会崩溃。原代码未启用无头模式,而PythonAnywhere没有GUI环境,无法渲染可视化的Chrome页面,必须修改代码启用无头模式才能避免崩溃。
  1. 该代码是否仅支持带GUI且安装Chrome的环境,能否在PythonAnywhere正常运行?
  • 原代码确实只支持带GUI的Chrome环境,但修改后可以在PythonAnywhere正常运行。需要调整ChromeDriver的配置,启用无头模式,并适配PythonAnywhere预装的Chromium路径,无需额外安装Chrome。

示例修改后的关键代码片段:

from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless=new")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
# 适配PythonAnywhere环境,无需指定executable_path(系统已配置)
driver = webdriver.Chrome(options=options)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:05:45