BeautifulSoup4庫
和 lxml 一樣,Beautiful Soup 也是一個HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 資料。
lxml 隻會局部周遊,而Beautiful Soup 是基于HTML DOM(Document Object Model)的,會載入整個文檔,解析整個DOM樹,是以時間和記憶體開銷都會大很多,是以性能要低于lxml。
BeautifulSoup 用來解析 HTML 比較簡單,API非常人性化,支援CSS選擇器、Python标準庫中的HTML解析器,也支援 lxml 的 XML解析器。
Beautiful Soup 3 目前已經停止開發,推薦現在的項目使用Beautiful Soup 4。
安裝和文檔:
- 安裝:
。pip install bs4
- 中文文檔:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
幾大解析工具對比:
解析工具 | 解析速度 | 使用難度 |
BeautifulSoup | 最慢 | 最簡單 |
lxml | 快 | 簡單 |
正則 | 最快 | 最難 |
簡單使用:
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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>
"""
#建立 Beautiful Soup 對象
# 使用lxml來進行解析
soup = BeautifulSoup(html,"lxml")
print(soup.prettify())
四個常用的對象:
Beautiful Soup将複雜HTML文檔轉換成一個複雜的樹形結構,每個節點都是Python對象,所有對象可以歸納為4種:
- Tag
- NavigatableString
- BeautifulSoup
- Comment
1. Tag:
Tag 通俗點講就是 HTML 中的一個個标簽。示例代碼如下:
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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>
"""
#建立 Beautiful Soup 對象
soup = BeautifulSoup(html,'lxml')
print soup.title
# <title>The Dormouse's story</title>
print soup.head
# <head><title>The Dormouse's story</title></head>
print soup.a
# <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
print soup.p
# <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
print type(soup.p)
# <class 'bs4.element.Tag'>
我們可以利用 soup 加标簽名輕松地擷取這些标簽的内容,這些對象的類型是bs4.element.Tag。但是注意,它查找的是在所有内容中的第一個符合要求的标簽。如果要查詢所有的标簽,後面會進行介紹。
對于Tag,它有兩個重要的屬性,分别是name和attrs。示例代碼如下:
print soup.name
# [document] #soup 對象本身比較特殊,它的 name 即為 [document]
print soup.head.name
# head #對于其他内部标簽,輸出的值便為标簽本身的名稱
print soup.p.attrs
# {'class': ['title'], 'name': 'dromouse'}
# 在這裡,我們把 p 标簽的所有屬性列印輸出了出來,得到的類型是一個字典。
print soup.p['class'] # soup.p.get('class')
# ['title'] #還可以利用get方法,傳入屬性的名稱,二者是等價的
soup.p['class'] = "newClass"
print soup.p # 可以對這些屬性和内容等等進行修改
# <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
2. NavigableString:
如果拿到标簽後,還想擷取标簽中的内容。那麼可以通過
tag.string
擷取标簽中的文字。示例代碼如下:
print soup.p.string
# The Dormouse's story
print type(soup.p.string)
# <class 'bs4.element.NavigableString'>thon
3. BeautifulSoup:
BeautifulSoup 對象表示的是一個文檔的全部内容.大部分時候,可以把它當作 Tag 對象,它支援 周遊文檔樹 和 搜尋文檔樹 中描述的大部分的方法.
因為 BeautifulSoup 對象并不是真正的HTML或XML的tag,是以它沒有name和attribute屬性.但有時檢視它的 .name 屬性是很友善的,是以 BeautifulSoup 對象包含了一個值為 “[document]” 的特殊屬性 .name
soup.name
# '[document]'
4. Comment:
Tag , NavigableString , BeautifulSoup 幾乎覆寫了html和xml中的所有内容,但是還有一些特殊對象.容易讓人擔心的内容是文檔的注釋部分:
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(markup)
comment = soup.b.string
type(comment)
# <class 'bs4.element.Comment'>
Comment 對象是一個特殊類型的 NavigableString 對象:
comment
# 'Hey, buddy. Want to buy a used parser'
周遊文檔樹:
1. contents和children:
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,'lxml')
head_tag = soup.head
# 傳回所有子節點的清單
print(head_tag.contents)
# 傳回所有子節點的疊代器
for child in head_tag.children:
print(child)
2. strings 和 stripped_strings
如果tag中包含多個字元串 [2] ,可以使用 .strings 來循環擷取:
for string in soup.strings:
print(repr(string))
# u"The Dormouse's story"
# u'\n\n'
# u"The Dormouse's story"
# u'\n\n'
# u'Once upon a time there were three little sisters; and their names were\n'
# 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'
輸出的字元串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多餘空白内容:
for string in soup.stripped_strings:
print(repr(string))
# u"The Dormouse's story"
# u"The Dormouse's story"
# u'Once upon a time there were three little sisters; and their names were'
# u'Elsie'
# u','
# u'Lacie'
# u'and'
# u'Tillie'
# u';\nand they lived at the bottom of a well.'
# u'...'
搜尋文檔樹:
1. find和find_all方法:
搜尋文檔樹,一般用得比較多的就是兩個方法,一個是
find
,一個是
find_all
。
find
方法是找到第一個滿足條件的标簽後就立即傳回,隻傳回一個元素。
find_all
方法是把所有滿足條件的标簽都選到,然後傳回回去。使用這兩個方法,最常用的用法是出入
name
以及
attr
參數找出符合要求的标簽。
soup.find_all("a",attrs={"id":"link2"})
或者是直接傳入屬性的的名字作為關鍵字參數:
soup.find_all("a",id='link2')
2. select方法:
使用以上方法可以友善的找出元素。但有時候使用
css
選擇器的方式可以更加的友善。使用
css
選擇器的文法,應該使用
select
方法。以下列出幾種常用的
css
選擇器方法:
(1)通過标簽名查找:
print(soup.select('a'))
(2)通過類名查找:
通過類名,則應該在類的前面加一個
.
。比如要查找
class=sister
的标簽。示例代碼如下:
print(soup.select('.sister'))
(3)通過id查找:
通過id查找,應該在id的名字前面加一個#号。示例代碼如下:
print(soup.select("#link1"))
(4)組合查找:
組合查找即和寫 class 檔案時,标簽名與類名、id名進行的組合原理是一樣的,例如查找 p 标簽中,id 等于 link1的内容,二者需要用空格分開:
print(soup.select("p #link1"))
直接子标簽查找,則使用 > 分隔:
print(soup.select("head > title"))
(5)通過屬性查找:
查找時還可以加入屬性元素,屬性需要用中括号括起來,注意屬性和标簽屬于同一節點,是以中間不能加空格,否則會無法比對到。示例代碼如下:
print(soup.select('a[href="http://example.com/elsie"]'))
(6)擷取内容
soup = BeautifulSoup(html, 'lxml')
print type(soup.select('title'))
print soup.select('title')[0].get_text()
for title in soup.select('title'):
print title.get_text()