当前位置: 移动技术网 > 网络运营>服务器>Linux > 基于linux配置selenium环境并实现运行

基于linux配置selenium环境并实现运行

2020年08月21日  | 移动技术网网络运营  | 我要评论
一、在linux中使用selenium1、安装chrome用下面的命令安装google chromeyum install https://dl.google.com/linux/direct/goo

一、在linux中使用selenium

1、安装chrome

用下面的命令安装google chrome

yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm

也可以先下载至本地,然后安装

wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum install ./google-chrome-stable_current_x86_64.rpm

安装必要的库

yum install mesa-libosmesa-devel gnu-free-sans-fonts wqy-zenhei-fonts

2、安装 chromedriver(末尾附chrome和chromedriver的对应版本)

chrome官网

wget https://chromedriver.storage.googleapis.com/2.38/chromedriver_linux64.zip

淘宝源(推荐)

wget http://npm.taobao.org/mirrors/chromedriver/2.41/chromedriver_linux64.zip

将下载的文件解压,放在如下位置

unzip chromedriver_linux64.zip
mv chromedriver /usr/bin/

给予执行权限

chmod +x /usr/bin/chromedriver

3、运行代码,查看是否成功(python下)

from selenium import webdriver
driver = webdriver.chrome()

------------2019年兼容版本对照表-----------
chromedriver 78.0.3904.11 (2019-09-12)---------supports chrome version 78
chromedriver 77.0.3865.40 (2019-08-20)---------supports chrome version 77
chromedriver 76.0.3809.12 (2019-06-07)---------supports chrome version 76
chromedriver 75.0.3770.8 (2019-04-29)---------supports chrome version 75
chromedriver v74.0.3729.6 (2019-03-14)--------supports chrome v74
chromedriver v2.46 (2019-02-01)----------supports chrome v71-73

二、chrome无界面模式运行

from selenium import webdriver
from selenium.webdriver.chrome.options import options
 
chrome_options = options()
chrome_options.add_argument('--no-sandbox')#解决devtoolsactiveport文件不存在的报错
chrome_options.add_argument('window-size=1920x3000') #指定浏览器分辨率
chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('--hide-scrollbars') #隐藏滚动条, 应对一些特殊页面
chrome_options.add_argument('blink-settings=imagesenabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
 
#创建浏览器对象
driver = webdriver.chrome(executable_path=path, chrome_options=chrome_options)#executable_path:浏览器驱动路径
driver.get(url)

三、无界面模式下下载文件

以前,以无头模式运行的chromedriver无法正确下载文件,原因是它稀疏地解析提供给它的首选项文件。无头chrome团队的工程师建议使用devtools的“ page.setdownloadbehavior”来解决此问题。此变更列表实现此修复程序。下载的文件默认为当前目录,可以在实例化chromedriver实例时使用download_dir进行设置。还添加了测试以确保正确的下载功能。

params = {'behavior': 'allow', 'downloadpath': r'c:\users\debanjan.b\downloads'}
driver.execute_cdp_cmd('page.setdownloadbehavior', params)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网