在Ubuntu系统上使用python的selenium,另外加上chrome和chromedriver,用于模拟浏览器访问网页。
下面教程在阿里云的Ubuntu 14.04 64位测试成功,其他linux系统大同小异。
安装chrome浏览器
1、更新系统
apt-get update
2、安装依赖
sudo apt-get install libxss1 libappindicator1 libindicator7
3、下载安装包
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
4、安装chrome
#经测试直接安装会报错,是dpkg的问题,需要先安装或更新dpkg
sudo apt-get install dpkg
# 安装chrome,安装过程中由于缺少一些依赖而报错是正常的
sudo dpkg -i google-chrome*.deb
#自动安装刚才缺少的依赖
sudo apt-get install -f
安装ChromeDriver
1、安装xvfb以便我们可以无头奔跑地运行Chrome
sudo apt-get install xvfb
2、安装zip解压缩工具,等下会用到
sudo apt-get install unzip
3、下载安装包,这里要重点注意,一定要下载最新版本的chromedriver,这样才能确保跟chrome的版本匹配。去chromedriver官网找到当前最新的版本号,如下图所示代表当前最新的版本号是81.0.4044.138
下载的时候只需要输入下面的命令即可,如果最新版本不是81.0.4044.138,只需要把下面81.0.4044.138替换成新版本的具体版本号即可。
wget -N https://chromedriver.storage.googleapis.com/81.0.4044.138/chromedriver_linux64.zip
4、解压缩刚下载的安装包
unzip chromedriver_linux64.zip
5、移动
sudo mv -f chromedriver /usr/local/share/chromedriver
6、建立软链接
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver
安装python的selenium以及其他相关依赖
1、如没有pip3,先执行安装
sudo apt-get install python3-pip
2、安装 selenium
pip3 install selenium
3、由于python自带的urllib3模块存在问题,所以需要更新或重新安装,否则等下在python里面使用chrome时会报错TypeError: urlopen() got multiple values for keyword argument 'body'
sudo pip3 install -U urllib3
测试通过python的selenium调用chrome
1、输入python3命令进入python3的交互式界面
python3
2、下面是python代码部分,可一行一行在交互式界面运行进行测试,也可保存到py文件后进行运行
#引入必需的模块
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#选项
chrome_options=Options()
#设置chrome浏览器为无界面模式
chrome_options.add_argument('--headless')
#下面的两行代码一般是不需要的,至少经过我的测试在windows上是不需要的。但经过我的测试在Ubuntu上如果不加的话等下就会报错WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser,所以要加上
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
#获取百度首页的标题
browser = webdriver.Chrome(options=chrome_options)
browser.get('http://www.baidu.com')
print(browser.title)