Python使用selenium + headless chrome获取网页内容的方法示例

yipeiwu_com5年前Python基础

使用python写爬虫时,优选selenium,由于PhantomJS因内部原因已经停止更新,最新版的selenium已经使用headless chrome替换掉了PhantomJS,所以建议将selenium更新到最新版,使用selenium + headless chrome

准备工作:

安装chrome、chrome driver、selenium

一、安装chrome

配置yum下载源,在目录/etc/yum.repos.d/下新建文件google-chrome.repo

> cd /ect/yum.repos.d/
> vim google-chrome.repo

编辑google-chrome.repo,内容如下,保存退出

[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

安装google chrome浏览器:

> yum -y install google-chrome-stable

PS: Google官方源可能在中国无法使用,导致安装失败或者在国内无法更新,可以添加以下参数来安装:

> yum -y install google-chrome-stable --nogpgcheck

这样,google chrome即可安装成功。

二、安装chrome driver

查看上述安装的chrome版本,根据版本选择对应的chrome driver下载,下载之后放到/usr/local/bin目录

三、安装selenium

> pip install selenium

上述准备工作完成后,就可以开始写代码了

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options


options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('lang=zh_CN.UTF-8')

# 在linux上需要添加一下两个参数
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

browser = Chrome(chrome_options=options)
browser.set_page_load_timeout(30)
browser.set_script_timeout(30)
browser.get(url)

# 获取返回内容
print browser.page_source

# 查找元素
print browser.find_element_by_tag_name('pre').text

备注:如果访问一些详情页有cookie验证,可以先访问主页,然后再访问详情页,webdriver会自动携带cookie

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

关于python多重赋值的小问题

前言 今天无意中发现在python中的一个多重赋值的小问题,自己一开始是比较简单化的理解了这个多重赋值操作的概念,所以导致在一道实现斐波那契数列的代码中,发现了自己的问题,顺便记录下吧,...

Windows中安装使用Virtualenv来创建独立Python环境

Windows中安装使用Virtualenv来创建独立Python环境

0、什么时候会用到virtualenv? 假设系统中的两个应用,其中A应用对库LibFoo的版本要求为1,而B应用对同一个库LibFoo的版本要求为2,两个应用对同一个库的要求想冲突了,...

使用url_helper简化Python中Django框架的url配置教程

django的url采用正则表达式进行配置,虽然强大却也广为诟病。反对者们认为django的url配置过于繁琐,且不支持默认的路由功能。 我倒觉得还好,只是如果觉得不爽,为什么不自己小小...

Python中请不要再用re.compile了

Python中请不要再用re.compile了

前言 如果大家在网上搜索Python 正则表达式,你将会看到大量的垃圾文章会这样写代码: import re pattern = re.compile('正则表达式') text...

深入了解Python枚举类型的相关知识

枚举类型可以看作是一种标签或是一系列常量的集合,通常用于表示某些特定的有限集合,例如星期、月份、状态等。 Python 的原生类型(Built-in types)里并没有专门的枚举类型,...