# 搜索文檔樹
Beautiful Soup定義了很多搜索方法,這里著重介紹2個: `find()` 和 `find_all()` .其它方法的參數和用法類似,請讀者舉一反三.
再以“愛麗絲”文檔作為例子:
```
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
```
使用 `find_all()` 類似的方法可以查找到想要查找的文檔內容
## 過濾器
介紹 `find_all()` 方法前,先介紹一下過濾器的類型 \[3\] ,這些過濾器貫穿整個搜索的API.過濾器可以被用在tag的name中,節點的屬性中,字符串中或他們的混合中.
### 字符串
最簡單的過濾器是字符串.在搜索方法中傳入一個字符串參數,Beautiful Soup會查找與字符串完整匹配的內容,下面的例子用于查找文檔中所有的`<b>`標簽:
```
soup.find_all('b')
# [<b>The Dormouse's story</b>]
```
如果傳入字節碼參數,Beautiful Soup會當作UTF-8編碼,可以傳入一段Unicode 編碼來避免Beautiful Soup解析編碼出錯
### 正則表達式
如果傳入正則表達式作為參數,Beautiful Soup會通過正則表達式的 `match()` 來匹配內容.下面例子中找出所有以b開頭的標簽,這表示`<body>`和`<b>`標簽都應該被找到:
```
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
# body
# b
```
下面代碼找出所有名字中包含”t”的標簽:
```
for tag in soup.find_all(re.compile("t")):
print(tag.name)
# html
# title
```
### 列表
如果傳入列表參數,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>]
```
### True
`True` 可以匹配任何值,下面代碼查找到所有的tag,但是不會返回字符串節點
```
for tag in soup.find_all(True):
print(tag.name)
# html
# head
# title
# body
# p
# b
# p
# a
# a
# a
# p
```
### 方法
如果沒有合適過濾器,那么還可以定義一個方法,方法只接受一個元素參數 \[4\] ,如果這個方法返回 `True` 表示當前元素匹配并且被找到,如果不是則反回 `False`
下面方法校驗了當前元素,如果包含 `class` 屬性卻不包含 `id` 屬性,那么將返回 `True`:
```
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
```
將這個方法作為參數傳入 `find_all()` 方法,將得到所有`<p>`標簽:
```
soup.find_all(has_class_but_no_id)
# [<p class="title"><b>The Dormouse's story</b></p>,
# <p class="story">Once upon a time there were...</p>,
# <p class="story">...</p>]
```
返回結果中只有`<p>`標簽沒有`<a>`標簽,因為`<a>`標簽還定義了”id”,沒有返回`<html>`和`<head>`,因為`<html>`和`<head>`中沒有定義”class”屬性.
下面代碼找到所有被文字包含的節點內容:
```
from bs4 import NavigableString
def surrounded_by_strings(tag):
return (isinstance(tag.next_element, NavigableString)
and isinstance(tag.previous_element, NavigableString))
for tag in soup.find_all(surrounded_by_strings):
print tag.name
# p
# a
# a
# a
# p
```
現在來了解一下搜索方法的細節
## find_all()
`find_all( name , attrs , recursive , text , **kwargs )`
`find_all()` 方法搜索當前tag的所有tag子節點,并判斷是否符合過濾器的條件.這里有幾個例子:
```
soup.find_all("title")
# [<title>The Dormouse's story</title>]
soup.find_all("p", "title")
# [<p class="title"><b>The Dormouse's story</b></p>]
soup.find_all("a")
# [<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>]
soup.find_all(id="link2")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
import re
soup.find(text=re.compile("sisters"))
# u'Once upon a time there were three little sisters; and their names were\n'
```
有幾個方法很相似,還有幾個方法是新的,參數中的 `text` 和 `id` 是什么含義? 為什么 `find_all("p", "title")` 返回的是CSS Class為”title”的`<p>`標簽? 我們來仔細看一下 `find_all()` 的參數
### name 參數
`name` 參數可以查找所有名字為 `name` 的tag,字符串對象會被自動忽略掉.
簡單的用法如下:
```
soup.find_all("title")
# [<title>The Dormouse's story</title>]
```
重申: 搜索 `name` 參數的值可以使任一類型的 [過濾器](#id25) ,字符竄,正則表達式,列表,方法或是 `True` .
### 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` 參數,Beautiful Soup會搜索每個tag的”href”屬性:
```
soup.find_all(href=re.compile("elsie"))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
```
搜索指定名字的屬性時可以使用的參數值包括 [字符串](#id27) , [正則表達式](#id28) , [列表](#id29), [True](#true) .
下面的例子在文檔樹中查找所有包含 `id` 屬性的tag,無論 `id` 的值是什么:
```
soup.find_all(id=True)
# [<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>]
```
使用多個指定名字的參數可以同時過濾tag的多個屬性:
```
soup.find_all(href=re.compile("elsie"), id='link1')
# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
```
有些tag屬性在搜索不能使用,比如HTML5中的 `data-*` 屬性:
```
data_soup = BeautifulSoup('foo!')
data_soup.find_all(data-foo="value")
# SyntaxError: keyword can't be an expression
```
但是可以通過 `find_all()` 方法的 `attrs` 參數定義一個字典參數來搜索包含特殊屬性的tag:
```
data_soup.find_all(attrs={"data-foo": "value"})
# [foo!]
```
### 按CSS搜索
按照CSS類名搜索tag的功能非常實用,但標識CSS類名的關鍵字 `class` 在Python中是保留字,使用 `class` 做參數會導致語法錯誤.從Beautiful Soup的4.1.1版本開始,可以通過 `class_` 參數搜索有指定CSS類名的tag:
```
soup.find_all("a", class_="sister")
# [<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>]
```
`class_` 參數同樣接受不同類型的 `過濾器` ,字符串,正則表達式,方法或 `True` :
```
soup.find_all(class_=re.compile("itl"))
# [<p class="title"><b>The Dormouse's story</b></p>]
def has_six_characters(css_class):
return css_class is not None and len(css_class) == 6
soup.find_all(class_=has_six_characters)
# [<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>]
```
tag的 `class` 屬性是 [多值屬性](#id12) .按照CSS類名搜索tag時,可以分別搜索tag中的每個CSS類名:
```
css_soup = BeautifulSoup('<p class="body strikeout"></p>')
css_soup.find_all("p", class_="strikeout")
# [<p class="body strikeout"></p>]
css_soup.find_all("p", class_="body")
# [<p class="body strikeout"></p>]
```
搜索 `class` 屬性時也可以通過CSS值完全匹配:
```
css_soup.find_all("p", class_="body strikeout")
# [<p class="body strikeout"></p>]
```
完全匹配 `class` 的值時,如果CSS類名的順序與實際不符,將搜索不到結果:
```
soup.find_all("a", attrs={"class": "sister"})
# [<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>]
```
### `text` 參數
通過 `text` 參數可以搜搜文檔中的字符串內容.與 `name` 參數的可選值一樣, `text` 參數接受 [字符串](#id27) , [正則表達式](#id28) , [列表](#id29), [True](#true) . 看例子:
```
soup.find_all(text="Elsie")
# [u'Elsie']
soup.find_all(text=["Tillie", "Elsie", "Lacie"])
# [u'Elsie', u'Lacie', u'Tillie']
soup.find_all(text=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"]
def is_the_only_string_within_a_tag(s):
""Return True if this string is the only child of its parent tag.""
return (s == s.parent.string)
soup.find_all(text=is_the_only_string_within_a_tag)
# [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...']
```
雖然 `text` 參數用于搜索字符串,還可以與其它參數混合使用來過濾tag.Beautiful Soup會找到 `.string` 方法與 `text` 參數值相符的tag.下面代碼用來搜索內容里面包含“Elsie”的`<a>`標簽:
```
soup.find_all("a", text="Elsie")
# [<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>]
```
### `limit` 參數
`find_all()` 方法返回全部的搜索結構,如果文檔樹很大那么搜索會很慢.如果我們不需要全部結果,可以使用 `limit` 參數限制返回結果的數量.效果與SQL中的limit關鍵字類似,當搜索到的結果數量達到 `limit` 的限制時,就停止搜索返回結果.
文檔樹中有3個tag符合搜索條件,但結果只返回了2個,因為我們限制了返回數量:
```
soup.find_all("a", limit=2)
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
```
### `recursive` 參數
調用tag的 `find_all()` 方法時,Beautiful Soup會檢索當前tag的所有子孫節點,如果只想搜索tag的直接子節點,可以使用參數 `recursive=False` .
一段簡單的文檔:
```
<html>
<head>
<title>
The Dormouse's story
</title>
</head>
...
```
是否使用 `recursive` 參數的搜索結果:
```
soup.html.find_all("title")
# [<title>The Dormouse's story</title>]
soup.html.find_all("title", recursive=False)
# []
```
## 像調用 `find_all()` 一樣調用tag
`find_all()` 幾乎是Beautiful Soup中最常用的搜索方法,所以我們定義了它的簡寫方法. `BeautifulSoup` 對象和 `tag` 對象可以被當作一個方法來使用,這個方法的執行結果與調用這個對象的 `find_all()` 方法相同,下面兩行代碼是等價的:
```
soup.find_all("a")
soup("a")
```
這兩行代碼也是等價的:
```
soup.title.find_all(text=True)
soup.title(text=True)
```
## find()
`find( name , attrs , recursive , text , **kwargs )`
`find_all()` 方法將返回文檔中符合條件的所有tag,盡管有時候我們只想得到一個結果.比如文檔中只有一個`<body>`標簽,那么使用 `find_all()` 方法來查找`<body>`標簽就不太合適, 使用 `find_all` 方法并設置 `limit=1` 參數不如直接使用 `find()` 方法.下面兩行代碼是等價的:
```
soup.find_all('title', limit=1)
# [<title>The Dormouse's story</title>]
soup.find('title')
# <title>The Dormouse's story</title>
```
唯一的區別是 `find_all()` 方法的返回結果是值包含一個元素的列表,而 `find()` 方法直接返回結果.
`find_all()` 方法沒有找到目標是返回空列表, `find()` 方法找不到目標時,返回 `None` .
```
print(soup.find("nosuchtag"))
# None
```
`soup.head.title` 是 [tag的名字](#id17) 方法的簡寫.這個簡寫的原理就是多次調用當前tag的 `find()` 方法:
```
soup.head.title
# <title>The Dormouse's story</title>
soup.find("head").find("title")
# <title>The Dormouse's story</title>
```
## find_parents() 和 find_parent()
`find_parents( name , attrs , recursive , text , **kwargs )`
`find_parent( name , attrs , recursive , text , **kwargs )`
我們已經用了很大篇幅來介紹 `find_all()` 和 `find()` 方法,Beautiful Soup中還有10個用于搜索的API.它們中的五個用的是與 `find_all()` 相同的搜索參數,另外5個與 `find()` 方法的搜索參數類似.區別僅是它們搜索文檔的不同部分.
記住: `find_all()` 和 `find()` 只搜索當前節點的所有子節點,孫子節點等. `find_parents()` 和 `find_parent()` 用來搜索當前節點的父輩節點,搜索方法與普通tag的搜索方法相同,搜索文檔搜索文檔包含的內容. 我們從一個文檔中的一個葉子節點開始:
```
a_string = soup.find(text="Lacie")
a_string
# u'Lacie'
a_string.find_parents("a")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
a_string.find_parent("p")
# <p class="story">Once upon a time there were three little sisters; and their names were
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
# and they lived at the bottom of a well.</p>
a_string.find_parents("p", class="title")
# []
```
文檔中的一個`<a>`標簽是是當前葉子節點的直接父節點,所以可以被找到.還有一個`<p>`標簽,是目標葉子節點的間接父輩節點,所以也可以被找到.包含class值為”title”的`<p>`標簽不是不是目標葉子節點的父輩節點,所以通過 `find_parents()` 方法搜索不到.
`find_parent()` 和 `find_parents()` 方法會讓人聯想到 [.parent](#parent) 和 [.parents](#parents) 屬性.它們之間的聯系非常緊密.搜索父輩節點的方法實際上就是對 `.parents` 屬性的迭代搜索.
## find_next_siblings() 合 find_next_sibling()
`find_next_siblings( name , attrs , recursive , text , **kwargs )`
`find_next_sibling( name , attrs , recursive , text , **kwargs )`
這2個方法通過 [.next_siblings](#next-siblings-previous-siblings) 屬性對當tag的所有后面解析 \[5\] 的兄弟tag節點進行迭代, `find_next_siblings()` 方法返回所有符合條件的后面的兄弟節點, `find_next_sibling()` 只返回符合條件的后面的第一個tag節點.
```
first_link = soup.a
first_link
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
first_link.find_next_siblings("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>]
first_story_paragraph = soup.find("p", "story")
first_story_paragraph.find_next_sibling("p")
# <p class="story">...</p>
```
## find_previous_siblings() 和 find_previous_sibling()
`find_previous_siblings( name , attrs , recursive , text , **kwargs )`
`find_previous_sibling( name , attrs , recursive , text , **kwargs )`
這2個方法通過 [.previous_siblings](#next-siblings-previous-siblings) 屬性對當前tag的前面解析 \[5\] 的兄弟tag節點進行迭代, `find_previous_siblings()` 方法返回所有符合條件的前面的兄弟節點, `find_previous_sibling()` 方法返回第一個符合條件的前面的兄弟節點:
```
last_link = soup.find("a", id="link3")
last_link
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
last_link.find_previous_siblings("a")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
first_story_paragraph = soup.find("p", "story")
first_story_paragraph.find_previous_sibling("p")
# <p class="title"><b>The Dormouse's story</b></p>
```
## find_all_next() 和 find_next()
`find_all_next( name , attrs , recursive , text , **kwargs )`
`find_next( name , attrs , recursive , text , **kwargs )`
這2個方法通過 [.next_elements](#next-elements-previous-elements) 屬性對當前tag的之后的 \[5\] tag和字符串進行迭代, `find_all_next()` 方法返回所有符合條件的節點, `find_next()` 方法返回第一個符合條件的節點:
```
first_link = soup.a
first_link
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
first_link.find_all_next(text=True)
# [u'Elsie', u',\n', u'Lacie', u' and\n', u'Tillie',
# u';\nand they lived at the bottom of a well.', u'\n\n', u'...', u'\n']
first_link.find_next("p")
# <p class="story">...</p>
```
第一個例子中,字符串 “Elsie”也被顯示出來,盡管它被包含在我們開始查找的`<a>`標簽的里面.第二個例子中,最后一個`<p>`標簽也被顯示出來,盡管它與我們開始查找位置的`<a>`標簽不屬于同一部分.例子中,搜索的重點是要匹配過濾器的條件,并且在文檔中出現的順序而不是開始查找的元素的位置.
## find_all_previous() 和 find_previous()
`find_all_previous( name , attrs , recursive , text , **kwargs )`
`find_previous( name , attrs , recursive , text , **kwargs )`
這2個方法通過 [.previous_elements](#next-elements-previous-elements) 屬性對當前節點前面 \[5\] 的tag和字符串進行迭代, `find_all_previous()` 方法返回所有符合條件的節點, `find_previous()` 方法返回第一個符合條件的節點.
```
first_link = soup.a
first_link
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
first_link.find_all_previous("p")
# [<p class="story">Once upon a time there were three little sisters; ...</p>,
# <p class="title"><b>The Dormouse's story</b></p>]
first_link.find_previous("title")
# <title>The Dormouse's story</title>
```
`find_all_previous("p")` 返回了文檔中的第一段(class=”title”的那段),但還返回了第二段,`<p>`標簽包含了我們開始查找的`<a>`標簽.不要驚訝,這段代碼的功能是查找所有出現在指定`<a>`標簽之前的`<p>`標簽,因為這個`<p>`標簽包含了開始的`<a>`標簽,所以`<p>`標簽一定是在`<a>`之前出現的.
## CSS選擇器
Beautiful Soup支持大部分的CSS選擇器 \[6\] ,在 `Tag` 或 `BeautifulSoup` 對象的 `.select()` 方法中傳入字符串參數,即可使用CSS選擇器的語法找到tag:
```
soup.select("title")
# [<title>The Dormouse's story</title>]
soup.select("p nth-of-type(3)")
# [<p class="story">...</p>]
```
通過tag標簽逐層查找:
```
soup.select("body a")
# [<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>]
soup.select("html head title")
# [<title>The Dormouse's story</title>]
```
找到某個tag標簽下的直接子標簽 \[6\] :
```
soup.select("head > title")
# [<title>The Dormouse's story</title>]
soup.select("p > a")
# [<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>]
soup.select("p > a:nth-of-type(2)")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
soup.select("p > #link1")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
soup.select("body > a")
# []
```
找到兄弟節點標簽:
```
soup.select("#link1 ~ .sister")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
soup.select("#link1 + .sister")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
```
通過CSS的類名查找:
```
soup.select(".sister")
# [<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>]
soup.select("[class~=sister]")
# [<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>]
```
通過tag的id查找:
```
soup.select("#link1")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
soup.select("a#link2")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
```
通過是否存在某個屬性來查找:
```
soup.select('a[href]')
# [<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>]
```
通過屬性的值來查找:
```
soup.select('a[href="http://example.com/elsie"]')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
soup.select('a[href^="http://example.com/"]')
# [<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>]
soup.select('a[href$="tillie"]')
# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
soup.select('a[href*=".com/el"]')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
```
通過語言設置來查找:
```
multilingual_markup = """
<p lang="en">Hello</p>
<p lang="en-us">Howdy, y'all</p>
<p lang="en-gb">Pip-pip, old fruit</p>
<p lang="fr">Bonjour mes amis</p>
"""
multilingual_soup = BeautifulSoup(multilingual_markup)
multilingual_soup.select('p[lang|=en]')
# [<p lang="en">Hello</p>,
# <p lang="en-us">Howdy, y'all</p>,
# <p lang="en-gb">Pip-pip, old fruit</p>]
```
對于熟悉CSS選擇器語法的人來說這是個非常方便的方法.Beautiful Soup也支持CSS選擇器API,如果你僅僅需要CSS選擇器的功能,那么直接使用 `lxml` 也可以,而且速度更快,支持更多的CSS選擇器語法,但Beautiful Soup整合了CSS選擇器的語法和自身方便使用API.