selenium+chromedriver在服务器运行的示例分析

发布时间:2021-07-30 09:23:21 作者:小新
来源:亿速云 阅读:114

这篇文章将为大家详细讲解有关selenium+chromedriver在服务器运行的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

1.前言

想使用selenium从网站上抓数据,但有时候使用phantomjs会出错。chrome现在也有无界面运行模式了,以后就可以不用phantomjs了。

但在服务器安装chrome时出现了一些错误,这里总结一下整个安装过程

2.ubuntu上安装chrome

# Install Google Chrome
# https://askubuntu.com/questions/79280/how-to-install-chrome-browser-properly-via-command-line
sudo apt-get install libxss1 libappindicator1 libindicator7
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome*.deb # Might show "errors", fixed by next line
sudo apt-get install -f

这时应该已经安装好了,用下边的命行运行测试一下:

google-chrome --headless --remote-debugging-port=9222 https://chromium.org --disable-gpu

这里是使用headless模式进行远程调试,ubuntu上大多没有gpu,所以–disable-gpu以免报错。
之后可以再打开一个ssh连接到服务器,使用命令行访问服务器的本地的9222端口:

curl http://localhost:9222

如果安装好了,会看到调试信息。但我这里会报一个错误,下边是错误的解决办法。

1)可能的错误解决方法

运行完上边的命令可能会报一个不能在root下运行chrome的错误。这个时候使用下边方设置一下chrome

1.找到google-chrome文件

我的位置位于/opt/google/chrome/

2.用vi打开google-chrome文件

vi /opt/google/chrome/google-chrome

在文件中找到

exec -a "$0" "$HERE/chrome" "$@"

3.在后面添加 –user-data-dir –no-sandbox即可,整条shell命令就是

exec -a "$0" "$HERE/chrome" "$@" --user-data-dir --no-sandbox

4.再重新打开google-chrome即可正常访问!

3.安装chrome驱动chromedriver

下载chromedriver

chromedriver提供了操作chrome的api,是selenium控制chrome的桥梁。

chromedriver最好安装最新版的,记的我一开始安装的不是最新版的,会报一个错。用最新版的chromedriver就没有问题,最新版的可以在下边地址找到
https://sites.google.com/a/chromium.org/chromedriver/downloads

我写这个文章时最新版是2.37

wget https://chromedriver.storage.googleapis.com/2.37/chromedriver_linux64.zip
unzip chromedriver_linux64.zip

到这里服务器端的无界面版chrome就安装好了。

4.无界面版chrome使用方法

from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument("user-agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'")
wd = webdriver.Chrome(chrome_options=chrome_options,executable_path='/home/chrome/chromedriver')

wd.get("https://www.163.com")

content = wd.page_source.encode('utf-8')
print content

wd.quit()

这里chrome_options中的第三项设置参数,使用这个设置可以避免网站检测到你使用的是无界模式进行反抓取。

下边另外的两项设置,不进行设置时在桌面版linux系统,或者mac系统上会打开有界面的chrome.调试时可以注释掉下边两行使用有界面版chrome来调试程序。

chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')

关于“selenium+chromedriver在服务器运行的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. JavaScript运行机制的示例分析
  2. js中运行机制的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

selenium chromedriver 服务器

上一篇:怎么用纯css实现的漂亮导航菜单

下一篇:如何使用Ubuntu Live CD修复Grub

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》