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 读取指定文件夹下的所有图像方法

(1)数据准备 数据集介绍: 数据集中存放的是1223幅图像,其中756个负样本(图像名称为0.1~0.756),458个正样本(图像名称为1.1~1.458),其中:"."前的标号为样...

python实现生成字符串大小写字母和数字的各种组合

1 输出大写字母、小写字母、大小写字母、数字、大小写字母和数字 1.1输出小写:找到小写a(97)到z(122)的的ASCII码,然后转义为字母 lower = "" for i i...

Scrapy的简单使用教程

Scrapy的简单使用教程

在这篇入门教程中,我们假定你已经安装了python。如果你还没有安装,那么请参考安装指南。 首先第一步:进入开发环境,workon article_spider 进入这个环境:...

python 链接和操作 memcache方法

1,打开memcached服务 memcached -m 10 -p 12000 2,使用python-memcached模块,进行简单的链接和存取数据 import me...

pip matplotlib报错equired packages can not be built解决

pip安装matplotlib 在centos6.5 64bit上用pip安装matplotlib时候报错: * The following required packages ca...