1、安装conda(通常conda内部自动安装了最新版的python和python-pip)
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash ~/Miniconda3-latest-Linux-x86_64.sh
source ~/.bashrc
conda list
2、安装selenium
pip install selenium
3、安装chrome和对应版本的chromedriver
可安装版本查看:googlechromelabs.github.io/chrome-for-…
下载chrome
wget https://storage.googleapis.com/chrome-for-testing-public/142.0.7444.175/linux64/chrome-linux64.zip
下载对应的chromedriver
wget https://storage.googleapis.com/chrome-for-testing-public/142.0.7444.175/linux64/chromedriver-linux64.zip
安装解压工具
yum install -y unzip zip
解压
unzip chrome-linux64.zip
unzip chromedriver-linux64.zip
修改执行权限
chmod +x /root/chromedriver-linux64/chromedriver
chmod +x /root/chrome-linux64/chrome
4、后台执行python脚本
nohup python -u scrape.py > console.out 2>&1 &
5、注意事项
执行若出现以下错误,说明权限可能有问题,解决方式如下: selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Chrome instance exited. Examine ChromeDriver verbose log to determine the cause.
解决方式:options.add_argument("--no-sandbox") # 给予root执行权限 另外由于是服务器上运行需要开启无头模式:options.add_argument("--headless") # 启用无头模式
6、验证代码示例
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
service = ChromeService(executable_path='../chromedriver-linux64/chromedriver') #指定本地的chromedriver
options = webdriver.ChromeOptions()
options.binary_location = r'/root/chrome-linux64/chrome' #指定本地的chrome浏览器
options.add_argument("--headless") # 启用无头模式
options.add_argument("--no-sandbox") # 给予root执行权限
# 设置驱动,启动浏览器
driver = webdriver.Chrome(service=service, options=options)
try:
driver.get('https://www.bing.com')
except Exception as e:
print("获取页面失败", e)
finally:
driver.quit()