Python + Selenium 完全可以在 Debian 上运行。大致流程分两步:

  1. 安装 Google Chrome 浏览器
  2. 安装 Python、Selenium 及对应的 ChromeDriver

下面以 Debian 11 (“Bullseye”) 为例,演示具体命令。

在 Debian 上安装 Google Chrome

Google 官方并不把 Chrome 放到 Debian 默认源,需要先添加 Google 的 apt 仓库。

# 1. 更新本地包列表
sudo apt update

# 2. 安装必要工具
sudo apt install -y wget gnupg2 apt-transport-https ca-certificates

# 3. 导入 Google 的公钥
wget -q -O - https://dl.google.com/linux/linux_signing_key.pub \
| sudo gpg --dearmor -o /usr/share/keyrings/google-linux-signing-keyring.gpg

# 4. 添加 Google Chrome 的 apt 源
echo "deb [signed-by=/usr/share/keyrings/google-linux-signing-keyring.gpg] \
http://dl.google.com/linux/chrome/deb/ stable main" \
| sudo tee /etc/apt/sources.list.d/google-chrome.list

# 5. 再次更新并安装 Chrome
sudo apt update
sudo apt install -y google-chrome-stable

安装完成后,你可以用 google-chrome --version 验证版本。

安装 Python、Selenium 及 ChromeDriver

安装 Python 和 pip

Debian 11 默认带有 Python3,但可以确保安装最新:

sudo apt install -y python3 python3-venv python3-pip

安装 Selenium

# 建议在 virtualenv 中安装
python3 -m venv ~/selenium-env
source ~/selenium-env/bin/activate

# 安装 Selenium 库
pip install --upgrade pip
pip install selenium

如果安装比较慢,可以使用国内镜像源:

pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

安装 ChromeDriver

ChromeDriver 必须与 Chrome 浏览器版本匹配。可手动下载,也可用 webdriver-manager 自动管理。

方案 A:手动下载
  1. 查询 Chrome 版本: google-chrome --version # 比如输出:Google Chrome 115.0.5790.98
  2. https://chromedriver.storage.googleapis.com/index.html 找到对应的 “115.0.5790.98” 版本,下载 Linux x64 zip。
  3. 解压并移动到 /usr/local/binwget -O chromedriver_linux64.zip \ https://chromedriver.storage.googleapis.com/115.0.5790.98/chromedriver_linux64.zip unzip chromedriver_linux64.zip sudo mv chromedriver /usr/local/bin/ sudo chmod +x /usr/local/bin/chromedriver
方案 B:自动管理(推荐开发环境)
pip install webdriver-manager

在脚本中使用时,示例代码:

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

# 自动下载并启动
service = Service(ChromeDriverManager().install())
options = webdriver.ChromeOptions()
# 如果在无头服务器上运行,加上下面两行:
# options.add_argument('--headless')
# options.add_argument('--no-sandbox')

driver = webdriver.Chrome(service=service, options=options)
driver.get("https://www.example.com")
print(driver.title)
driver.quit()

完成以上步骤后,就可以在 Debian 上用 Python + Selenium + ChromeDriver 驱动真实的 Chrome 浏览器来做自动化测试或爬虫/RPA 了。

0

本文为原创文章,转载请注明出处,欢迎访问作者网站(和而不同)

发表评论

error: Content is protected !!