现在越来越多的应用和互联网产品做内容的聚合,像今日头条、等等,太多的聚合应用以及不胜枚举,甚至浏览器也可以嵌入聚合的应用。
互联网上拥有太多太多的数据,抓取网页的数据做数据挖掘也是最廉价的获取数据的途径,解析数据是得到规则数据的方法,他为后面数据挖掘、机器学习模型的学习提供支持。
在获取互联网数据的过程中,不可避免的就要使用到网页爬虫技术,此外在抓取下来的网页,需要进一步的解析出自己想要的内容。正则表达式是最常用的解析工具,针对网页目前有个非常便捷的框架,叫做BeautifulSoup。本文使用的是BeautifulSoup 3,现在已经有BeautifulSoup4了,名字改为bs4
(1)下载与安装
# BeautifulSoup 的下载与安装
pip install BeautifulSoup
另外也可以下载安装包进行安装
(2)快速开始
# BeautifulSoup 快速开始
html_doc = urllib2.urlopen('http://baike.baidu.com/view/1059363.htm')
soup = BeautifulSoup(html_doc)
print soup.title
结果:
# BeautifulSoup 结果
前门大街_百度百科
(3)BeautifulSoup对象介绍
BeautifulSoup中主要包含三种类型的对象:
BeautifulSoup.BeautifulSoup
BeautifulSoup.Tag
BeautifulSoup.NavigableString
通过下面例子来认识上面的三种数据类型:
# BeautifulSoup 示例
from BeautifulSoup import BeautifulSoup
import urllib2
html_doc = urllib2.urlopen('http://www.baidu.com')
soup = BeautifulSoup(html_doc)
print type(soup)
print type(soup.title)
print type(soup.title.string)
print soup.title
print soup.title.string
结果为
# BeautifulSoup 示例结果
百度一下,你就知道 百度一下,你就知道
print soup.title
print soup.title.string
从上面的例子可以比较清晰的看到BeautifulSoup主要包括三种类型的对象。
BeautifulSoup.BeautifulSoup //BeautifulSoup对象
BeautifulSoup.Tag //标签对象
BeautifulSoup.NavigableString //导航string文本对象
(4)BeautifulSoup剖析树
1. BeautifulSoup.Tag对象方法
获取标记对象,通过点号获取Tag对象
# BeautifulSoup 示例
title = soup.title
print type(title.contents)
print title.contents
print title.contents[0]
# BeautifulSoup 示例结果
[u'\u767e\u5ea6\u4e00\u4e0b\uff0c\u4f60\u5c31\u77e5\u9053']
百度一下,你就知道
contents方法
获得当前标签的内容list,如果该标签没有子标签,那么string方法和contents[0]得到的内容是一样的。见上面示例
next,parent方法
获得当前的标签的子标签和父标签
# BeautifulSoup 示例
html = soup.html
print html.next
print ''
print html.next.next
print html.next.next.nextSibling
# BeautifulSoup 示例结果
百度一下,你就知道 ......
nextSibling,previousSibling
获得当前标签的下一个兄弟标签和前一个兄弟标签
对不同的网页,将你需要的标签中的数据,例如评论、阅读量、购买量、价格、数量等等,通过BS解析获得。解析是数据获取整理过程中不可少的一部分。
进一步的,借助机器学习模型对上述数据进行建模分析,得到一定的结论。