Python3.x的BeautifulSoup解析html常用函数
1,初始化:
soup = BeautifulSoup(html) #html为html源代码字符串,type(html) == str
2,用tag获取相应代码块的剖析树:
#当用tag作为搜索条件时,我们获取的包含这个tag块的剖析树:#ooo#这里获取head这个块
head = soup.find('head')#or#head = soup.head#or#head = soup.contents[0].contents[0]
contents属性是一个列表,里面保存了该剖析树的直接儿子,如:
html = soup.contents[0] # ...
head = html.contents[0] #
...body = html.contents[1] #
...3,用contents[], parent, nextSibling, previousSibling寻找父子兄弟tag:
beautifulSoup提供了几个简单的方法直接获取当前tag块的父子兄弟。
假设我们已经获得了body这个tag块,我们想要寻找,
, 第一个, 第二个
这四个tag块:
#body = soup.bodyhtml = body.parent # html是body的父亲
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]也可得到
print(p1.text)#u'This is paragraphone.'
print(p2.text)#u'This is paragraphtwo.'#注意:1,每个tag的text包括了它以及它子孙的text。2,所有text已经被自动转#为unicode,如果需要,可以自行转码encode(xxx)
4,用find, findParent, findNextSibling, findPreviousSibling寻找祖先或者子孙 tag:
find方法(我理解和findChild是一样的),就是以当前节点为起始,遍历整个子树,找到后返回。
而这些方法的复数形式,会找到所有符合要求的tag,以list的方式放回。他们的对应关系是:find->findall, findParent->findParents, findNextSibling->findNextSiblings...,如:
print soup.findAll('p')#[
This is paragraph one.
,This is paragraph two.
](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
(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属性的
(3),搜索文字(text):
注意:文字的搜索会导致其他搜索给的值如:tag, attrs都失效。
方法与搜索tag一致;
(4),recursive, limit:
recursive=False表示只搜索直接儿子,否则搜索整个子树,默认为True。
当使用findAll或者类似返回list的方法时,limit属性用于限制返回的数量,如findAll('p', limit=2): 返回首先找到的两个tag