Python中Beautifulsoup学习笔记二

1、用tag获取相应代码块的剖析树:

contents属性是一个列表,里面保存了该剖析树的直接儿子。

如:
1 html = soup.contents[0] # <html> ... </html>
2 head = html.contents[0] # <head> ... </head>
3 body = html.contents[1] # <body> ... </body>

2、用contents[], parent, nextSibling, previousSibling寻找父子兄弟tag

为了更加方便灵活的分析html代码块,beautifulSoup提供了几个简单的方法直接获取当前tag块的父子兄弟。

假设我们已经获得了body这个tag块,我们想要寻找<html>, <head>, 第一个<p>, 第二个<p>这四个tag块:

 

3、用find, findParent, findNextSibling, findPreviousSibling寻找祖先或者子孙 tag:

有了上面的基础,这里应该很好理解了,例如find方法(我理解和findChild是一样的),就是以当前节点为起始,遍历整个子树,找到后返回。

  而这些方法的复数形式,会找到所有符合要求的tag,以list的方式放回。他们的对应关系是:find->findall, findParent->findParents, findNextSibling->findNextSiblings...

 

里我们重点讲一下find的几种用法,其他的类比:

  find(name=None, attrs={}, recursive=True, text=None, **kwargs)

(ps:只讲几种用法,完整请看官方link :http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#The%20basic%20find%20method:%20findAll%28name,%20attrs,%20recursive,%20text,%20limit,%20**kwargs%29

  1) 搜索tag:

1 find(tagname)        # 直接搜索名为tagname的tag 如:find('head')
2 find(list)           # 搜索在list中的tag,如: find(['head', 'body'])
3 find(dict)           # 搜索在dict中的tag,如:find({'head':True, 'body':True})
4 find(re.compile('')) # 搜索符合正则的tag, 如:find(re.compile('^p')) 搜索以p开头的tag
5 find(lambda)         # 搜索函数返回结果为true的tag, 如:find(lambda name: if len(name) == 1) 搜索长度为1的tag
6 find(True)           # 搜索所有tag

 2) 搜索属性(attrs):

1 find(id='xxx')                                  # 寻找id属性为xxx的
2 find(attrs={id=re.compile('xxx'), algin='xxx'}) # 寻找id属性符合正则且algin属性为xxx的
3 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

 

参考链接:http://www.cnblogs.com/twinsclover/archive/2012/04/26/2471704.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章