官方文档:http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html


1. 初始化

1.1 导入模块

#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup       #process html
from BeautifulSoup import BeautifulStoneSoup  #process xml
import BeautifulSoup                          #all


1.2 创建对象

doc = ['<html><head>hello<title>PythonClub.org</title></head>',
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b> of ptyhonclub.org.',
       '<p id="secondpara" align="blah">This is paragraph <b>two</b> of pythonclub.org.',
       '</html>']
soup = BeautifulSoup(''.join(doc))


指定编码:

htmlCharset = "GB2312"
soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset)



2.获取tag内容 (以下3种方法等价)

head = soup.find('head')
head = soup.head
head = soup.contents[0].contents[0]
print head


3.获取关系节点

3.1 使用parent获取父节点

body = soup.body

html = body.parent             # html是body的父亲

3.2 使用nextSibling, previousSibling获取前后兄弟

head = body.previousSibling    # head和body在同一层,是body的前一个兄弟

p1 = body.contents[0]          # p1, p2都是body的儿子,我们用contents[0]取得p1

p2 = p1.nextSibling            # p2与p1在同一层,是p1的后一个兄弟, 当然body.content[1]也可得到



4.find/findAll用法详解

函数原型:find(name=None, attrs={}, recursive=True, text=None, **kwargs),findAll会返回所有符合要求的结果,并以list返回

第一个是tag的名称,第二个是属性。第3个选择递归,text是判断内容。limit是提取数量限制。**kwargs 就是字典传递了


4.1 tag搜索

find(tagname)    # 直接搜索名为tagname的tag 如:find('head')

find(list)       # 搜索在list中的tag,如: find(['head', 'body'])

find(dict)       # 搜索在dict中的tag,如:find({'head':True, 'body':True})

find(re.compile(''))    # 搜索符合正则的tag, 如:find(re.compile('^p')) 搜索以p开头的tag

find(lambda)     # 搜索函数返回结果为true的tag, 如:find(lambda name: if len(name) == 1) 搜索长度为1的tag

find(True)       # 搜索所有tag,但是不会返回字符串节点

findAll(name, attrs, recursive, text, limit, **kwargs)


示例:

a = urllib2.urlopen('http://www.baidu.com')
b = a.read().decode('utf-8')
soup = BeautifulSoup.BeautifulStoneSoup(b,convertEntities=BeautifulSoup.BeautifulStoneSoup.ALL_ENTITIES).html.head.findAll('link')
for i in soup:
    print i['href']


4.2 attrs搜索

find(id='xxx')                                  # 寻找id属性为xxx的

find(attrs={id=re.compile('xxx'), algin='xxx'}) # 寻找id属性符合正则且algin属性为xxx的

find(attrs={id=True, algin=None})               # 寻找有id属性但是没有algin属性的


4.3 text搜索

文字的搜索会导致其他搜索给的值如:tag, attrs都失效。方法与搜索tag一致

print p1.text

# u'This is paragraphone.'

print p2.text

# u'This is paragraphtwo.'

# 注意:1,每个tag的text包括了它以及它子孙的text。2,所有text已经被自动转为unicode,如果需要,可以自行转码encode(xxx)


4.4 recursive和limit属性

recursive=False表示只搜索直接儿子,否则搜索整个子树,默认为True

当使用findAll或者类似返回list的方法时,limit属性用于限制返回的数量,如findAll('p', limit=2): 返回首先找到的两个tag