文章來源[Python爬蟲利器二之Beautiful Soup的用法 | 靜覓](http://cuiqingcai.com/1319.htmlhtml
首先必需要導入 bs4 庫python
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
咱們建立一個字符串,後面的例子咱們便會用它來演示正則表達式
Pythonexpress
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> """
建立 beautifulsoup 對象函數
soup = BeautifulSoup(html, "lxml")
另外,咱們還能夠用本地 HTML 文件來建立對象,例如ui
soup = BeautifulSoup(open('index.html'), "lxml")
上面這句代碼即是將本地 index.html 文件打開,用它來建立 soup 對象
下面咱們來打印一下 soup 對象的內容,格式化輸出翻譯
print soup.prettify()
<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 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> </body> </html>
以上即是輸出結果,格式化打印出了它的內容,這個函數常常用到,小夥伴們要記好咯。code
Beautiful Soup將複雜HTML文檔轉換成一個複雜的樹形結構,每一個節點都是Python對象,全部對象能夠概括爲4種:orm
Tagxml
NavigableString
BeautifulSoup
Comment
下面咱們進行一一介紹
Tag 是什麼?通俗點講就是 HTML 中的一個個標籤,例如
<title>The Dormouse's story</title> <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
上面的 title a 等等 HTML 標籤加上裏面包括的內容就是 Tag,下面咱們來感覺一下怎樣用 Beautiful Soup 來方便地獲取 Tags
下面每一段代碼中註釋部分即爲運行結果
print soup.title # <title>The Dormouse's story</title>
print soup.title # <title>The Dormouse's story</title>
print soup.head # <head><title>The Dormouse's story</title></head>
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.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 soup.p # <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
咱們能夠利用 soup加標籤名輕鬆地獲取這些標籤的內容,是否是感受比正則表達式方便多了?不過有一點是,它查找的是在全部內容中的第一個符合要求的標籤,若是要查詢全部的標籤,咱們在後面進行介紹。
咱們能夠驗證一下這些對象的類型
print type(soup.a) # <class 'bs4.element.Tag'>
print type(soup.a) # <class 'bs4.element.Tag'>
對於 Tag,它有兩個重要的屬性,是 name 和 attrs,下面咱們分別來感覺一下
name
print soup.name print soup.head.name # [document] # head
soup 對象自己比較特殊,它的 name 即爲 [document],對於其餘內部標籤,輸出的值便爲標籤自己的名稱。
attrs
print soup.p.attrs # {'class': ['title'], 'name': 'dromouse'} print soup.p.attrs # {'class': ['title'], 'name': 'dromouse'}
在這裏,咱們把 p 標籤的全部屬性打印輸出了出來,獲得的類型是一個字典。
若是咱們想要單獨獲取某個屬性,能夠這樣,例如咱們獲取它的 class 叫什麼
print soup.p['class'] # ['title'] print soup.p['class'] # ['title']
還能夠這樣,利用get方法,傳入屬性的名稱,兩者是等價的
print soup.p.get('class') # ['title'] print soup.p.get('class') # ['title']
咱們能夠對這些屬性和內容等等進行修改,例如
soup.p['class']="newClass" print soup.p # <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
還能夠對這個屬性進行刪除,例如
del soup.p['class'] print soup.p # <p name="dromouse"><b>The Dormouse's story</b></p>
不過,對於修改刪除的操做,不是咱們的主要用途,在此不作詳細介紹了,若是有須要,請查看前面提供的官方文檔
既然咱們已經獲得了標籤的內容,那麼問題來了,咱們要想獲取標籤內部的文字怎麼辦呢?很簡單,用 .string 便可,例如
print soup.p.string # The Dormouse's story
這樣咱們就輕鬆獲取到了標籤裏面的內容,想一想若是用正則表達式要多麻煩。它的類型是一個 NavigableString,翻譯過來叫 能夠遍歷的字符串,不過咱們最好仍是稱它英文名字吧。
來檢查一下它的類型
print type(soup.p.string) # <class 'bs4.element.NavigableString'>
BeautifulSoup 對象表示的是一個文檔的所有內容.大部分時候,能夠把它看成 Tag 對象,是一個特殊的 Tag,咱們能夠分別獲取它的類型,名稱,以及屬性來感覺一下
print type(soup.name) # <type 'unicode'> print soup.name # [document] print soup.attrs # {} 空字典
Comment 對象是一個特殊類型的 NavigableString 對象,其實輸出的內容仍然不包括註釋符號,可是若是很差好處理它,可能會對咱們的文本處理形成意想不到的麻煩。
咱們找一個帶註釋的標籤
print soup.a print soup.a.string print type(soup.a.string)
運行結果以下
<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> Elsie <class 'bs4.element.Comment'>
a 標籤裏的內容其實是註釋,可是若是咱們利用 .string 來輸出它的內容,咱們發現它已經把註釋符號去掉了,因此這可能會給咱們帶來沒必要要的麻煩。
另外咱們打印輸出下它的類型,發現它是一個 Comment 類型,因此,咱們在使用前最好作一下判斷,判斷代碼以下
if type(soup.a.string)==bs4.element.Comment: print soup.a.string
上面的代碼中,咱們首先判斷了它的類型,是否爲 Comment 類型,而後再進行其餘操做,如打印輸出。
要點:.contents .children 屬性
.contents
tag 的 .content 屬性能夠將tag的子節點以列表的方式輸出
print soup.head.contents # [<title>The Dormouse's story</title>]
輸出方式爲列表,咱們能夠用列表索引來獲取它的某一個元素
print soup.head.contents[0] # <title>The Dormouse's story</title>
.children
它返回的不是一個 list,不過咱們能夠經過遍歷獲取全部子節點。
咱們打印輸出 .children 看一下,能夠發現它是一個 list 生成器對象
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
知識點:.descendants 屬性
.descendants
.contents 和 .children 屬性僅包含tag的直接子節點,.descendants 屬性能夠對全部tag的子孫節點進行遞歸循環,和 children相似,咱們也須要遍歷獲取其中的內容。
for child in soup.descendants: print child
運行結果以下,能夠發現,全部的節點都被打印出來了,先生最外層的 HTML標籤,其次從 head 標籤一個個剝離,以此類推。
<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 class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
知識點:.string 屬性
若是tag只有一個 NavigableString 類型子節點,那麼這個tag可使用 .string 獲得子節點。若是一個tag僅有一個子節點,那麼這個tag也可使用 .string 方法,輸出結果與當前惟一子節點的 .string 結果相同。
通俗點說就是:若是一個標籤裏面沒有標籤了,那麼 .string 就會返回標籤裏面的內容。若是標籤裏面只有惟一的一個標籤了,那麼 .string 也會返回最裏面的內容。例如
print soup.head.string # The Dormouse's story print soup.title.string # The Dormouse's story
若是tag包含了多個子節點,tag就沒法肯定,string 方法應該調用哪一個子節點的內容, .string 的輸出結果是 None
print soup.html.string # None
知識點: .strings .stripped_strings 屬性
.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
輸出的字符串中可能包含了不少空格或空行,使用 .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'...'
知識點: .parent 屬性
p = soup.p print p.parent.name #body
content = soup.head.title.string print content.parent.name # title
知識點:.parents 屬性
經過元素的 .parents 屬性能夠遞歸獲得元素的全部父輩節點,例如
content = soup.head.title.string for parent in content.parents: print parent.name
title head html [document]
知識點:.next_sibling .previous_sibling 屬性
兄弟節點能夠理解爲和本節點處在統一級的節點,.next_sibling 屬性獲取了該節點的下一個兄弟節點,.previous_sibling 則與之相反,若是節點不存在,則返回 None
注意:實際文檔中的tag的 .next_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 屬性
經過 .next_siblings 和 .previous_siblings 屬性能夠對當前節點的兄弟節點迭代輸出
for sibling in soup.a.next_siblings: print(repr(sibling)) # u',\n' # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> # u' and\n' # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> # u'; and they lived at the bottom of a well.' # None
知識點:.next_element .previous_element 屬性
與 .next_sibling .previous_sibling 不一樣,它並非針對於兄弟節點,而是在全部節點,不分層次
好比 head 節點爲
<head><title>The Dormouse's story</title></head>
那麼它的下一個節點即是 title,它是不分層次關係的
print soup.head.next_element # <title>The Dormouse's story</title>
知識點:.next_elements .previous_elements 屬性
經過 .next_elements 和 .previous_elements 的迭代器就能夠向前或向後訪問文檔的解析內容,就好像文檔正在被解析同樣
for element in last_a_tag.next_elements: print(repr(element)) # u'Tillie' # u';\nand they lived at the bottom of a well.' # u'\n\n' # <p class="story">...</p> # u'...' # u'\n' # None
以上是遍歷文檔樹的基本用法。
find_all() 方法搜索當前tag的全部tag子節點,並判斷是否符合過濾器的條件
1)name 參數
name 參數能夠查找全部名字爲 name 的tag,字符串對象會被自動忽略掉
A.傳字符串
最簡單的過濾器是字符串.在搜索方法中傳入一個字符串參數,Beautiful Soup會查找與字符串完整匹配的內容,下面的例子用於查找文檔中全部的標籤
soup.find_all('b') # [<b>The Dormouse's story</b>]
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>]
B.傳正則表達式
若是傳入正則表達式做爲參數,Beautiful Soup會經過正則表達式的 match() 來匹配內容.下面例子中找出全部以b開頭的標籤,這表示<body>和標籤都應該被找到
import re for tag in soup.find_all(re.compile("^b")): print(tag.name) # body # b
C.傳列表
若是傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回.下面代碼找到文檔中全部標籤和標籤
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.傳方法
若是沒有合適過濾器,那麼還能夠定義一個方法,方法只接受一個元素參數 [[4]](http://www.crummy.com/softwar... ,若是這個方法返回 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>]
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 參數,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>]
有些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>]
3)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"]
4)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>]
5)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() 方法惟一的區別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回結果
find_all() 和 find() 只搜索當前節點的全部子節點,孫子節點等. find_parents() 和 find_parent() 用來搜索當前節點的父輩節點,搜索方法與普通tag的搜索方法相同,搜索文檔搜索文檔包含的內容
這2個方法經過 .next_siblings 屬性對當 tag 的全部後面解析的兄弟 tag 節點進行迭代, find_next_siblings() 方法返回全部符合條件的後面的兄弟節點,find_next_sibling() 只返回符合條件的後面的第一個tag節點
這2個方法經過 .previous_siblings 屬性對當前 tag 的前面解析的兄弟 tag 節點進行迭代, find_previous_siblings() 方法返回全部符合條件的前面的兄弟節點, find_previous_sibling() 方法返回第一個符合條件的前面的兄弟節點
這2個方法經過 .next_elements 屬性對當前 tag 的以後的 tag 和字符串進行迭代, find_all_next() 方法返回全部符合條件的節點, find_next() 方法返回第一個符合條件的節點
這2個方法經過 .previous_elements 屬性對當前節點前面的 tag 和字符串進行迭代, find_all_previous() 方法返回全部符合條件的節點, find_previous()方法返回第一個符合條件的節點
注:以上(2)(3)(4)(5)(6)(7)方法參數用法與 find_all() 徹底相同,原理均相似,在此再也不贅述。
咱們在寫 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>]
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 方法返回的結果都是列表形式,能夠遍歷形式輸出,而後用 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()