服务器配置selenium

安装chrome浏览器

1
2
3
4
5
6
7
8
# 下载安装包
$ wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

# 安装chrome
$ sudo dpkg -i google-chrome-stable_current_amd64.deb

# 检查版本
$ google-chrome --version

安装chromedriver

1
2
3
4
5
6
7
8
9
10
11
12
13
# chromedriver地址
https://registry.npmmirror.com/binary.html?path=chrome-for-testing

# 下载驱动
wget https://storage.googleapis.com/chrome-for-testing-public/123.0.6312.86/linux64/chrome-linux64.zip

# 解压
$ unzip chromedriver-linux64.zip

# 移动位置(也可以不移,添加到环境变量或者程序中指定位置)
cd chromedriver-linux64
mv chromedriver /usr/bin

无头模式网页加载不出/过慢

  • 更新selenium库
    使用conda安装的selenium库版本比较老,使用pip安装和更新
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 配置selenium=4.12
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
# 配置 Chrome 选项
option = Options()
# 新版本的无头模式
option.add_argument('--headless=new')
# 禁用gpu
option.add_argument('--disable-gpu')
# 解决DevToolsActivePort文件不存在的报错
option.add_argument('--no-sandbox')
option.add_argument('--disable-dev-shm-usage')
# 解决user-agent过短
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
option.add_argument(f'user-agent={user_agent}')
option.add_argument("--window-size=1920,1050")

# 指定 chromedriver 的路径
chromedriver_path = '/home/ubuntu/chromedriver/chromedriver-linux64/chromedriver'

# 使用指定的 chromedriver 路径和选项启动 WebDriver
driver=webdriver.Chrome(service=Service(chromedriver_path), options=option)
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2023-2025 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信