python模組系列==6、BeautifulSoup
BeautifulSoup簡介
我們知道,Python擁有出色的內建HTML解析器模組——HTMLParser,然而還有一個功能更為強大的HTML或XML解析工具——BeautifulSoup(美味的湯),它是一個第三方庫。簡單來說,BeautifulSoup最主要的功能是從網頁抓取資料。本文我們來感受一下BeautifulSoup的優雅而強大的功能吧!
BeautifulSoup安裝
BeautifulSoup3 目前已經停止更新,推薦在現在的專案中使用BeautifulSoup4,不過它已經被移植到bs4了。也就是說匯入時我們需要 import bs4 。可以利用 pip 或者 easy_install 兩種方法來安裝。下面採用pip安裝。
pip install beautifulsoup4
pip install lxml
建議同時安裝"lxml"模組,BeautifulSoup支援Python標準庫中的HTML解析器("html.parser"),還支援一些第三方的解析器,如果我們不安裝它,則 Python 會使用 Python預設的解析器,lxml 解析器更加強大,速度更快,推薦安裝。
建立物件
安裝後,建立物件:soup = BeautifulSoup(markup='類html字串', 'lxml') # 這裡有個坑,"lxml" 解析器會將所有節點名稱轉為小寫!使用 "xml" 解析器則不會轉換。
格式化輸出:soup.prettify()
BeautifulSoup四大物件型別
BeautifulSoup將複雜HTML文件轉換成一個複雜的樹形結構,每個節點都是Python物件,所有物件可以歸納為4種:
- BeautifulSoup(文件)
- Tag(標籤)
- NavigableString(內容)
- Comment(註釋)
1.BeautifulSoup型別(文件)
BeautifulSoup物件表示的是一個文件的全部內容:
print soup.name # [document]
2.Tag型別(標籤)
即HTML的整個標籤,如獲取<title>標籤:
print soup.title #<title>The Dormouse's story</title>
Tag有兩個重要屬性:name,attrs。
name
即HTML的標籤名稱:
print soup.name #[document] print soup.head.name #head
attrs
即HTML的標籤屬性字典:
print soup.p.attrs #{'class': ['title'], 'name': 'dromouse'}
如果想要單獨獲取某個屬性:
print soup.p['class'] #['title']
3.NavigableString型別(內容)
既然我們已經得到了整個標籤,那麼問題來了,我們要想獲取標籤內部的文字內容怎麼辦呢?很簡單,用 string 即可:
print soup.p.string #The Dormouse's story
4.Comment型別(註釋)
HTML的註釋內容,注意的是,不包含註釋符號。我們首先判斷它的型別,是否為 Comment 型別,然後再進行其他操作,如列印輸出:
if type(soup.a.string)==bs4.element.Comment: print soup.a.string #<!-- Elsie -->
遍歷文件樹
1.子節點
contents
獲取所有子節點,返回列表:
print soup.head.contents #[<title>The Dormouse's story</title>]
children
獲取所有子節點,返回列表生成器:
print soup.head.children #<listiterator object at 0x7f71457f5710> ## 需要遍歷 for child in soup.body.children: print child ## 結果 <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 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> <p class="story">...</p>
2.節點內容
string
返回單個文字內容。如果一個標籤裡面沒有標籤了,那麼 string 就會返回標籤裡面的內容。如果標籤裡面只有唯一的一個標籤了,那麼 string 也會返回最裡面的內容。如果tag包含了多個子節點,tag就無法確定,string方法應該呼叫哪個子節點的內容,string的輸出結果是 None。例如:
print soup.head.string print soup.title.string #The Dormouse's story #The Dormouse's story
print soup.html.string
# None
strings
返回多個文字內容,且包含空行和空格。
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'...'
get_text()方法
返回當前節點和子節點的文字內容。
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <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="sister1" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister2" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister3" id="link3">Tillie</a>; and they lived at the bottom of a well. </p> <p class="story">...</p> </body> </html> """ soup = BeautifulSoup(markup=html_doc,features='lxml') node_p_text=soup.find('p',class_='story').get_text() # 注意class_帶下劃線 print(node_p_text) # 結果 Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.
3.父節點
parent
返回某節點的直接父節點:
p = soup.p print p.parent.name #body
parents
返回某節點的所有父輩及以上輩的節點:
content = soup.head.title.string for parent in content.parents: print parent.name ## 結果 title head html [document]
4.兄弟節點
next_sibling
next_sibling 屬性獲取該節點的下一個兄弟節點,結果通常是字串或空白,因為空白或者換行也可以被視作一個節點。
previous_sibling
previous_sibling 屬性獲取該節點的上一個兄弟節點。
print soup.p.next_sibling # 實際該處為空白 print soup.p.prev_sibling #None 沒有前一個兄弟節點,返回 None print soup.p.next_sibling.next_sibling #<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> #下一個節點的下一個兄弟節點是我們可以看到的節點
next_siblings、previous_siblings
迭代獲取全部兄弟節點。
5.前後節點
next_element、previous_element
不是針對於兄弟節點,而是在於所有節點,不分層次的前一個和後一個節點。
next_elements、previous_elements
迭代獲取所有前和後節點。
搜尋文件樹
1.find_all(name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)
find_all()方法搜尋當前tag的所有tag子節點,並判斷是否符合過濾器的條件。
引數說明
name引數
name引數很強大,可以傳多種方式的引數,查詢所有名字為 name 的tag,字串物件會被自動忽略掉。
(a)傳標籤名
最簡單的過濾器是標籤名。在搜尋方法中傳入一個標籤名引數,BeautifulSoup會查詢與標籤名完整匹配的內容,下面的例子用於查詢文件中所有的<a>標籤:
print 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>]
返回結果列表中的元素仍然是BeautifulSoup物件。
(b)傳正則表示式
如果傳入正則表示式作為引數,BeautifulSoup會通過正則表示式的 match() 來匹配內容。下面例子中找出所有以b開頭的標籤,這表示<body>和<b>標籤都應該被找到:
import re for tag in soup.find_all(re.compile("^b")): print(tag.name) # body # b
(c)傳列表
如果傳入列表引數,BeautifulSoup會將與列表中任一元素匹配的內容返回。下面程式碼找到文件中所有<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>]
(d)傳True
True 可以匹配任何值,下面程式碼查詢到所有的tag,但是不會返回字串節點:
for tag in soup.find_all(True): print(tag.name) # html # head # title # body # p # b # p # a # a
(e)傳函式
如果沒有合適過濾器,那麼還可以定義一個方法,方法只接受一個元素引數。如果這個方法返回 True 表示當前元素匹配並且被找到,如果不是則反回 False:
def has_class_but_no_id(tag): return tag.has_attr('class') and not tag.has_attr('id') 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>]
keyword引數
注意的是,如果一個指定名字的引數不是搜尋內建的引數名,搜尋時會把該引數當作指定名字tag的屬性來搜尋,如果包含一個名字為 id 的引數,BeautifulSoup會搜尋每個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>]
使用多個指定名字的引數可以同時過濾tag的多個屬性:
soup.find_all(href=re.compile("elsie"), id='link1') # [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
在這裡我們想用 class 過濾,不過 class 是 python 的關鍵詞,這怎麼辦?加個下劃線就可以:
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>]
attrs引數
有些tag屬性在搜尋不能使用,比如HTML5中的 "data-*" 自定義屬性:
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>') 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"}) # [<div data-foo="value">foo!</div>]
text引數
通過 text 引數可以搜搜文件中的字串內容。與 name 引數的可選值一樣,text 引數接受字串 、正則表示式 、列表、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"]
limit引數
find_all() 方法返回全部的搜尋結構,如果文件樹很大那麼搜尋會很慢。如果我們不需要全部結果,可以使用 limit 引數限制返回結果的數量。效果與SQL中的limit關鍵字類似,當搜尋到的結果數量達到 limit 的限制時,就停止搜尋返回結果。
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() 方法時,BeautifulSoup會檢索當前tag的所有子孫節點,如果只想搜尋tag的直接子節點,可以使用引數 recursive=False。
soup.html.find_all("title") # [<title>The Dormouse's story</title>] soup.html.find_all("title", recursive=False) # []
2.find( name , attrs , recursive , text , **kwargs )
它與 find_all() 方法唯一的區別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回結果。
3.find_parents() 和 find_parent()
find_all() 和 find() 只搜尋當前節點的所有子節點,孫子節點等。find_parents() 和 find_parent() 用來搜尋當前節點的父輩節點,搜尋方法與普通tag的搜尋方法相同,搜尋文件搜尋文件包含的內容。
4.find_next_siblings() 和 find_next_sibling()
這2個方法通過 .next_siblings 屬性對當 tag 的所有後面解析的兄弟 tag 節點進行迭代, find_next_siblings() 方法返回所有符合條件的後面的兄弟節點,find_next_sibling() 只返回符合條件的後面的第一個tag節點。
5.find_previous_siblings() 和 find_previous_sibling()
這2個方法通過 .previous_siblings 屬性對當前 tag 的前面解析的兄弟 tag 節點進行迭代, find_previous_siblings() 方法返回所有符合條件的前面的兄弟節點,find_previous_sibling() 方法返回第一個符合條件的前面的兄弟節點。
6.find_all_next() 和 find_next()
這2個方法通過 .next_elements 屬性對當前 tag 的之後的 tag 和字串進行迭代, find_all_next() 方法返回所有符合條件的節點, find_next() 方法返回第一個符合條件的節點。
7.find_all_previous() 和 find_previous()
這2個方法通過 .previous_elements 屬性對當前節點前面的 tag 和字串進行迭代,find_all_previous() 方法返回所有符合條件的節點, find_previous()方法返回第一個符合條件的節點。
CSS選擇器
我們在寫 CSS 時,標籤名不加任何修飾,類名前加點,id名前加 #,在這裡我們也可以利用類似的方法來篩選元素,用到的方法是 soup.select(),返回型別是 list。
通過標籤名查詢
print soup.select('title') #[<title>The Dormouse's story</title>] print soup.select('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>] print soup.select('b') #[<b>The Dormouse's story</b>]
通過類名查詢
print 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>]
通過 id 名查詢
print soup.select('#link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
組合查詢
組合查詢即和寫 class 檔案時,標籤名與類名、id名進行的組合原理是一樣的,例如查詢 p 標籤中,id 等於 link1的內容,二者需要用空格分開。
print soup.select('p #link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
直接子標籤查詢:
print soup.select("head > title") #[<title>The Dormouse's story</title>]
屬性查詢
查詢時還可以加入屬性元素,屬性需要用中括號括起來,注意屬性和標籤屬於同一節點,所以中間不能加空格,否則會無法匹配到。
print soup.select('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>] print soup.select('a[href="http://example.com/elsie"]') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
同樣,屬性仍然可以與上述查詢方式組合,不在同一節點的空格隔開,同一節點的不加空格:
print soup.select('p a[href="http://example.com/elsie"]') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
以上的 select 方法返回的結果都是列表形式,可以遍歷形式輸出,然後用 string或get_text()方法來獲取它的內容:
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()
修改文件樹
1.修改.string
給Tag的 .string 屬性賦值,就相當於用當前的內容替代了原來的內容。(如果當前的Tag包含了其它tag,那麼給它的 .string 屬性賦值會覆蓋掉原有的所有內容包括子Tag)。
如,soup.find('title').string = '新標題'
2.append()
Tag.append() 方法向Tag中新增子內容,與Python的列表的 append() 方法用法相同。
如,soup.find('p').append('段落內容')
3.new_tag()
建立一個Tag最好的方法是呼叫工廠方法 BeautifulSoup.new_tag()。
如,soup.find('p').append(soup.new_tag('a', href='http://www.baidu.com'))
4.insert()、insert_before() 和 insert_after()
把元素插入到指定的位置。
如,soup.find('p').insert_after(soup.new_tag('a', href='http://www.baidu.com'))
5.decompose()
Tag.decompose() 方法將當前節點完全移除。
6.clear()
Tag.clear() 方法清空當前節點的內容