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

yipeiwu_com6年前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中的cookielib模拟登录网站

前面简单提到了 Python 模拟登录的程序,但是没写清楚,这里再补上一个带注释的 Python 模拟登录的示例程序。简单说一下流程:先用cookielib获取cookie,再用获取到的...

python-opencv获取二值图像轮廓及中心点坐标的代码

python-opencv获取二值图像轮廓及中心点坐标代码: groundtruth = cv2.imread(groundtruth_path)[:, :, 0] h1, w1 =...

Python代码缩进和测试模块示例详解

前言 Python代码缩进和测试模块是大家学习python必不可少的一部分,本文主要介绍了关于Python代码缩进和测试模块的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看...

浅谈使用Python变量时要避免的3个错误

Python编程中经常遇到一些莫名其妙的错误, 其实这不是语言本身的问题, 而是我们忽略了语言本身的一些特性导致的,今天就来看下使用Python变量时导致的3个不可思议的错误, 以后在编...

python读取并定位excel数据坐标系详解

python读取并定位excel数据坐标系详解

测试数据:坐标数据:testExcelData.xlsx 使用python读取excel文件需要安装xlrd库: xlrd下载后的压缩文件:xlrd-1.2.0.tar.gz 解压后再...