如何在无GUI的全新Linux机器上用Python配置Selenium与ChromeDriver?
在无GUI全新Linux机器上配置Python+Selenium+ChromeDriver
1. 更新系统并安装基础依赖
先完成系统包更新,再安装Python、pip及工具包:
sudo apt update && sudo apt upgrade -y sudo apt install python3 python3-pip unzip wget -y # 安装Chrome运行所需的依赖库 sudo apt install libxss1 libappindicator1 libindicator7 -y
2. 安装无头Chrome浏览器
无GUI环境需安装支持headless模式的Chrome,执行以下命令:
# 下载Chrome稳定版安装包 wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb # 安装Chrome sudo dpkg -i google-chrome-stable_current_amd64.deb # 自动修复依赖缺失 sudo apt --fix-broken install -y # 验证安装结果 google-chrome --version
若偏好Chromium,可直接执行:sudo apt install chromium-browser -y
3. 匹配安装ChromeDriver
ChromeDriver版本必须与Chrome主版本一致,按以下步骤操作:
# 提取Chrome主版本号 CHROME_VERSION=$(google-chrome --version | grep -oP '\d+\.\d+\.\d+') # 下载对应版本的ChromeDriver(Linux 64位) wget https://storage.googleapis.com/chrome-for-testing-public/$CHROME_VERSION/linux64/chromedriver-linux64.zip # 解压压缩包 unzip chromedriver-linux64.zip # 将ChromeDriver移至系统可执行路径 sudo mv chromedriver-linux64/chromedriver /usr/local/bin/ # 赋予执行权限 sudo chmod +x /usr/local/bin/chromedriver # 验证安装结果 chromedriver --version
4. 安装Python Selenium库
用pip安装最新版Selenium:
pip3 install selenium --user
5. 验证配置有效性
创建测试脚本test_selenium.py:
from selenium import webdriver from selenium.webdriver.chrome.options import Options # 配置Chrome无头模式参数 chrome_options = Options() chrome_options.add_argument('--headless=new') # Selenium 4.8+推荐的新无头模式 chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') # 初始化浏览器实例 driver = webdriver.Chrome(options=chrome_options) # 测试访问示例页面 driver.get('https://www.example.com') print("页面标题:", driver.title) # 关闭浏览器 driver.quit()
运行脚本验证:
python3 test_selenium.py
若输出页面标题: Example Domain,则配置成功。
常见问题排查
- 版本不匹配:重新提取Chrome版本号,下载对应版本的ChromeDriver即可。
- 权限问题:确保
/usr/local/bin/有写入权限,或使用--user参数将ChromeDriver放入用户目录并添加至PATH。 - 依赖缺失:运行时若提示缺少库,用
sudo apt install [缺失库名]安装即可。
内容的提问来源于stack exchange,提问作者Emmanuel Lopez
相关产品推荐
相关产品推荐

