1. 程式人生 > >爬蟲庫之BeautifulSoup學習(四)

爬蟲庫之BeautifulSoup學習(四)

所有 字符串 判斷 href gin int 過濾器 amp link

探索文檔樹:

find_all(name,attrs,recursive,text,**kwargs)

方法搜索當前tag的所有tag子節點,並判斷是否符合過濾器的條件

1、name參數,可以查找所有名字為name的tag,字符串對象會被自動忽略掉。

1) 傳字符串

最簡單的過濾器是字符串.在搜索方法中傳入一個字符串參數,Beautiful Soup會查找與字符串完整匹配的內容.

下面的例子用於查找文檔中所有的<b>標簽

soup.find_all(‘b‘)

# [<b>The Dormouse‘s story</b>]

2)傳正則表達式

如果傳入正則表達式作為參數,Beautiful Soup會通過正則表達式的 match() 來匹配內容.

下面例子中找出所有以b開頭的標簽,這表示<body>和<b>標簽都應該被找到

import re

for tag in soup.find_all(re.compile("^b")):

  print tag.name

#body

#b

3)傳列表

如果傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回.下面代碼找到文檔中所有<a>標簽和<b>標簽

soup.find_all(["a","b"])

# [<b>The Dormouse‘s story</b>,
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

4)傳True

可以匹配任何值,下面代碼查找到所有的tag,但是不會返回字符串節點

5)傳方法

2.keyword參數

  註意:如果一個指定名字的參數不是搜索內置的參數名,搜索時會把該參數當作指定名字tag的屬性來搜索,如果包含一個名字為 id 的參數,Beautiful Soup會搜索每個tag的”id”屬性

  soup.find_all(id=‘link2‘)

  # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

  

  如果傳入href參數,BeautifulSoup會搜索每個tag的"href"屬性

  soup.find_all(href=re.compile("elsie"))

  使用多個指定名字的參數可以同時過濾tag的多個屬性

  soup.find_all(href=re.compile("elsie"),id=‘link1)

  

  

爬蟲庫之BeautifulSoup學習(四)