Python爬虫——Beautiful Soup的用法

Python爬虫——Beautiful Soup的用法


学习自崔庆才的个人博客静觅
文章地址:http://cuiqingcai.com/1319.html

0. Beautiful Soup简介及环境配置

Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据,所以可以用这个库来实现爬虫功能。

下载地址:https://pypi.python.org/pypi/beautifulsoup4/4.3.2

下载后解压至硬盘里,然后打开命令行,进入对应文件夹,执行python setup.py install进行安装。

Beautiful Soup中文文档:

http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

1. 创建Beautiful Soup对象

导入bs4库from bs4 import BeautifulSoup

然后创建BeautifulSoup对象soup=BeautifulSoup(html),这里的参数是一个网页文本,或者是一个类文件对象,如open(),urlopen()都可以。另外现在需要在后面加一个参数'lxml',所以实例化的格式如下:soup=BeautifulSoup(urllib2.urlopen('http://www.baidu.com').read(),'lxml')

下来是将soup对象的内容打印出来:print soup.prettify()

2. 四大对象种类

Beautiful Soup将HTML文档转换成了复杂的树形结构,每个节点都是Python对象。共有四种对象,tag,NavigableString,BeautifulSoup,Comment

  1. tag

通过实例感受:

html = """
The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names were , Lacie and Tillie; and they lived at the bottom of a well.

...

""" soup=BeautifulSoup(html) #title tag之间的内容 print soup.title #head之间的内容 print soup.head #通过soup加标签名获取标签之间的内容 #Tag对象有两个属性,name与attrs print soup.head.name #输出是head print soup.p.attrs #输出是字典{'class': ['title'], 'name': 'dromouse'} #单独获取属性 print soup.p['class'] print soup.p.get('class') #修改这些属性 soup.p['class']='newClass' #删除属性 del soup.p['class']
  1. NavigableString

通过这样soup.p.string获取标签内部的文字

print soup.p.string
#输出是The Dormouse's story
  1. BeautifulSoup

该对象表示的是一个文档的全部内容,大部分情况可以当成Tag对象,是一个特殊的Tag,实例感受:

print type(soup.name)
#输出是
print soup.name
 #输出是[document]
print soup.attrs
#输出是空字典[]
  1. Comment

Comment对象是一个特殊类型的NavigableString对象,使用soup.a.string打印将不包括注释符号,所以在打印之前,判断是否是bs4.element.Comment,再进行其他操作。

if type(soup.a.string)==bs4.element.Comment:
    print soup.a.string

3. 遍历文档树

  1. .contents .children .descendants属性

仍然是上实例:

#.contents属性将tag的子节点以列表方式输出
print soup.head.contents
#输出方式为列表,以最大的标签内容为一个列表项
#对于html.contents来说列表包含head和body
#可以用列表索引获取元素
print soup.head.contents[0]

#.children属性返回的是列表迭代器,遍历所有子节点
for child in soup.body.children:
    print child

#.descendants属性将遍历所有tag的子孙节点
for child in soup.descendants:
    print child
#重点是每一个标签层层剥离

未完待续

你可能感兴趣的:(Python爬虫——Beautiful Soup的用法)