【避坑 超详细】Ubuntu使用python的selenium以及chrome模拟真实浏览器访问网页

在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)

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值