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>],数据基本上就可以被获取了。

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

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

 

转载于:https://www.cnblogs.com/ACSeeker/p/6445513.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值