通过Selenium和PhantomJS抓取带JS的网页

爬虫一般通过获取网页的源码,然后通过正则表达式或html解释器获取所需的信息,但是有的网页,不能直接通过 linux下的 wget 命令、或者使用 Python 中的requests.get这样的函数库来直接获取其真正展现给用户的信息,因为里面包含有JavaScript脚本,而该JS和页面数据的生成相关,需要通过Firefox、Chrome等浏览器渲染后才能得到想要看的结果。

如亚马逊的商品列表 https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=lightning+cable 通过上面提到的方法直接获取其网页源码是无法获取每个商品的标题信息的。

一般来说,对于这种网页如下两种方案: 1. 通过Selenium启动真正的浏览器(如:IE、Firefox)来打开该网页,然后调用webdriver获取想要的页面元素。 2. 通过浏览器渲染引擎解释网页,能够让其解析网页并执行网页中需要初始化JS,然后将JS、CSS等执行后的HTML代码输出出来。

启动真正的浏览器,可能带来两个问题:一个是需要的时间较长,另一个是UI自动化易受干扰、不够稳定。因此本文主要讲述通过第二种方法,也就是不启动浏览器进行获取这种网页上的信息。

主要用到的库是Selenium,通过selenium 中的 PhantomJS 作为webdriver能够不启动浏览器来解释js文件并获取其解释后的源码。下面以上面的亚马逊商品列表页作为例子,通过PhantomJS来获取其页面上的商品标题。

首先需要在官网下载PhantomJS的可执行文件。

然后获取页面 https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=lightning+cable 上的商品列表的python代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding: utf-8 -*-
# @Author: LC
# @Date: 2016-07-30 10:08:31
# @Last modified by: LC
# @Last Modified time: 2016-08-22 17:08:46
# @Email: liangchaowu5@gmail.com

from selenium import webdriver
from bs4 import BeautifulSoup

target_url = r'https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=lightning+cable'
driver = webdriver.PhantomJS(executable_path = r'H:/PythonModule/phantomjs/phantomjs-2.1.1-windows/bin/phantomjs.exe')
driver.get(target_url)
text = driver.page_source # 获取解释后的网页源码
soup = BeautifulSoup(text, 'lxml')
titles = soup.find_all('h2')
for title in titles:
print title.get('data-attribute', '')
driver.quit()

上面的代码首先通过指定本地的PhantomJS的可执行文件可解释目标url,获取其网页html代码,然后通过BeautifulSoup提取网页代码中的商品标题


参考:http://smilejay.com/2013/12/try-phantomjs-with-selenium/