python爬虫笔记:phantomjs+selenium采集内容

对于一般的网站而言,利用python的beautifulsoup都可以爬取,但面对一些需要执行页面上的JavaScript才能爬取的网站,就可以采用phantomjs+selenium的方法爬取数据。我在学习时,也遇到了这类问题,因此聊以记之。

我用的案例网站是中国天气网(http://www.weather.com.cn/weather40d/101020100.shtml)。

我想爬取的是 上海的40天天气里的每一天的最高气温数据。因此,首先我使用一般的方法爬取:

from bs4 import BeautifulSoup
from urllib.request import urlopen
html = urlopen('http://www.weather.com.cn/weather40d/101020100.shtml')
html_parse = BeautifulSoup(html)
temp = html_parse.findAll("span",{"class":"max"})
print(temp)

但是却发现print(temp)输出的只是标签:[<span class="max"></span>, <span class="max"></span>...... <span class="max"></span>]

因此我判断数据必须要在javascript执行后才能获取,于是,我采用了phantomjs+selenium的方式获取这一类数据,代码如下:

from bs4 import BeautifulSoup
from selenium import webdriver
import time

driver = webdriver.PhantomJS(executable_path='F:\\python\\phantomjs-2.1.1-windows\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe')
driver.get("http://www.weather.com.cn/weather40d/101020100.shtml")
time.sleep(3)
pageSource = driver.page_source
html_parse = BeautifulSoup(pageSource)
temp = html_parse.findAll("span",{"class":"max"})
print(temp)

这段代码创建了一个新的selenium WebDriver,首先用WebDriver加载页面,因此我们给它3秒钟时间(time.sleep(3)),之后,由于我个人比较喜欢用beautifulsoup,而WebDriver的page_source函数可以返回页面的源代码字符串,因此我用了第8,9行代码来回归到用我们所熟悉的Beautifulsoup来解析页面内容。这个程序的最后运行结果是:[<span class="max">9</span>, <span class="max">9</span>...... <span class="max">12</span>, <span class="max">12</span>, <span class="max"></span>, <span class="max"></span>, <span class="max"></span>, <span class="max"></span>, <span class="max"></span>, <span class="max"></span>, <span class="max"></span>],数据基本上就可以被获取了。

虽然这个例子比较简单,但是所谓万变不离其宗,其基本思想便是这些了,更高深的技术就需要我们继续学习了。

若文中有错误不妥之处,欢迎指出,共同学习,一起进步。

 

posted @ 2017-02-26 19:30  ACSeeker  阅读(3235)  评论(0编辑  收藏  举报