如何在Ubuntu上部署最新的Google Chrome和ChromeDriver

1,573 阅读1分钟

本章将帮助各位同学如何在Ubuntu及衍生版安装ChromeDriver和Selenium。

准备

执行以下命令以在系统上安装所需的软件包。这里 Xvfb(X 虚拟帧缓冲区)是用于类 UNIX 操作系统(例如 Linux)的内存显示服务器。它实现了没有任何显示的 X11 显示服务器协议。这对于 CI 服务等 CLI 应用程序很有帮助。

$ sudo apt update 
$ sudo apt install -y unzip xvfb libxi6 libgconf-2-4 

安装 Chrome

$ sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add 
$ sudo bash -c "echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' >> /etc/apt/sources.list.d/google-chrome.list" 
$ sudo apt -y update 
$ sudo apt -y install google-chrome-stable 

安装 ChromeDriver

查看 Chrome版本

$ google-chrome --version 
Google Chrome 122.0.6261.111

官网只有115及以下的支持版本 我找到一个文件可以找到最新版的 ChromeDriver。通过Wget、curl或aria2下载chromedriver_linux64.zip

解压

$ unzip chromedriver_linux64.zip 

部署

$ sudo mv chromedriver /usr/bin/chromedriver 
$ sudo chown root:root /usr/bin/chromedriver 
$ sudo chmod +x /usr/bin/chromedriver 

Python selenium

代码

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

service = Service(executable_path='/usr/bin/chromedriver')
options = Options()
options.add_argument("--no-sandbox")
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--window-size=1920,1080")
driver = webdriver.Chrome(service=service, options=options)

driver.get('https://www.python.org/')