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设计模式之桥接模式原理与用法实例分析

本文实例讲述了Python设计模式之桥接模式原理与用法。分享给大家供大家参考,具体如下: 桥接模式(Bridge Pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化....

python钉钉机器人运维脚本监控实例

python钉钉机器人运维脚本监控实例

如下所示: #!/usr/bin/python3 # -*- coding:UTF-8-*- # Author: zhuhongqiang from urllib impor...

解决uWSGI的编码问题详解

发现问题 最近工作中遇到一个问题,在把 Flask 写的应用通过 Supervisor+uWSGI 部署到正式服务器上时,出现了这样的错误: Unable to print the...

Numpy掩码式数组详解

数据很大形况下是凌乱的,并且含有空白的或者无法处理的字符,掩码式数组可以很好的忽略残缺的或者是无效的数据点。掩码式数组由一个正常数组与一个布尔式数组组成,若布尔数组中为Ture,则表示正...

在OpenCV里使用Camshift算法的实现

在OpenCV里使用Camshift算法的实现

前面学习过Meanshift算法,在观察这个结果标记时,会发现有这样一个问题,如下图: 汽车比较远时,用一个很小的窗口就可以把它框住,这是符合近大远小的投影原理,当比较近的时候如下:...