爬蟲提取規則之Beautiful Soup的使用

安裝

pip install beautifulsoup4
easy_install beautifulsoup4
apt-get install Python-bs4 //Debian或者ubuntu系統安裝方法

Beautiful Soup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,其中一個是 lxml .根據操作系統不同,可以選擇下列方法來安裝lxml:

$ apt-get install Python-lxml
$ easy_install lxml
$ pip install lxml

另一個可供選擇的解析器是純Python實現的 html5lib , html5lib的解析方式與瀏覽器相同,可以選擇下列方法來安裝html5lib:

$ apt-get install Python-html5lib
$ easy_install html5lib
$ pip install html5lib

在這裏插入圖片描述

使用方法

from bs4 import BeautifulSoup
soup = BeautifulSoup(open("index.html"))
soup = BeautifulSoup("<html>data</html>")

首先,文檔被轉換成Unicode,並且HTML的實例都被轉換成Unicode編碼。
然後,Beautiful Soup選擇最合適的解析器來解析這段文檔,如果手動指定解析器那麼Beautiful Soup會選擇指定的解析器來解析文檔。

Beautiful Soup將複雜HTML文檔轉換成一個複雜的樹形結構,每個節點都是Python對象,所有對象可以歸納爲4種:

四大對象

Tag

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>
"""

soup = BeautifulSoup(html)
Tag就是標籤,你可以通過標籤很快的對值進行提取
常見的標籤有

>>> soup.a
<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
>>> soup.p   
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
>>> soup.head
<head><title>The Dormouse's story</title></head>
>>> soup.title   
<title>The Dormouse's story</title>

NavigableString

如果想要獲取標籤內的文字,用 .string就可以

>>> soup.a.string
' Elsie '

Comment

Comment 對象是一個特殊類型的 NavigableString 對象,其實輸出的內容仍然不包括註釋符號,但是如果不好好處理它,可能會對我們的文本處理造成意想不到的麻煩。

我們找一個帶註釋的標籤

>>> print(type(soup.a.string))
<class 'bs4.element.Comment'>

BeautifulSoup

BeautifulSoup 對象表示的是一個文檔的全部內容.大部分時候,可以把它當作 Tag 對象,是一個特殊的 Tag,我們可以分別獲取它的類型,名稱,以及屬性來感受一下

print(type(soup.name))
#<type 'unicode'>
print(soup.name) 
# [document]
print(soup.attrs)
#{} 空字典

遍歷文檔樹

(1)直接子節點

.contents

tag 的 .content 屬性可以將tag的子節點以列表的方式輸出

>>> print(soup.head.contents)
[<title>The Dormouse's story</title>]

.children

它返回的不是一個 list,不過我們可以通過遍歷獲取所有子節點。
我們打印輸出 .children 看一下,可以發現它是一個 list 生成器對象

>>> print(soup.head.children)
<list_iterator object at 0x00000159583C3F28>

要想輸出內容的話需要用迭代器

>>> 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)所有子孫節點

.descendants

.contents 和 .children 屬性僅包含tag的直接子節點,.descendants 屬性可以對所有tag的子孫節點進行遞歸循環,和 children類似,我們也需要遍歷獲取其中的內容。

for child in soup.descendants:
    print(child)

(3)節點內容
如果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

(4)多個內容

.strings

獲取多個內容,不過需要遍歷獲取,比如下面的例子

>>> for string in soup.strings:
	 print(repr(string))
"The Dormouse's story"
'\n'
'\n'
"The Dormouse's story"
'\n'
'Once upon a time there were three little sisters; and their names were\n'
',\n'
'Lacie'
' and\n'
'Tillie'
';\nand they lived at the bottom of a well.'
'\n'
'...'
'\n'
>>> 

.stripped_strings

輸出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多餘空白內容

>>> for string in soup.stripped_strings:
	 print(repr(string))
"The Dormouse's story"
"The Dormouse's story"
'Once upon a time there were three little sisters; and their names were'
','
'Lacie'
'and'
'Tillie'
';\nand they lived at the bottom of a well.'

(5)父節點

.parent

>>> p = soup.p
>>> print(p.parent.name)
body

(6)全部父節點

.parents

通過元素的 .parents 屬性可以遞歸得到元素的所有父輩節點,例如

>>> content = soup.head.title.string
>>> for parent in  content.parents:
	 print (parent.name)
title
head
html
[document]

(7)兄弟節點

next_sibling/prev_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>
下一個節點的下一個兄弟節點是我們可以看到的節點

(8)全部兄弟節點

.next_siblings /.previous_siblings

通過 .next_siblings 和 .previous_siblings 屬性可以對當前節點的兄弟節點迭代輸出

>>> for sibling in soup.a.next_siblings:
	 print(repr(sibling))
',\n'
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
' and\n'
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
';\nand they lived at the bottom of a well.'

(9)前後節點

.next_element /.previous_element

與 .next_sibling .previous_sibling 不同,它並不是針對於兄弟節點,而是在所有節點,不分層次

>>> print(soup.head.next_element)
<title>The Dormouse's story</title>

(10)所有前後節點

.next_elements /.previous_elements

通過 .next_elements 和 .previous_elements 的迭代器就可以向前或向後訪問文檔的解析內容,就好像文檔正在被解析一樣

搜索文檔樹

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

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

1)name 參數

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

A.傳字符串

最簡單的過濾器是字符串.在搜索方法中傳入一個字符串參數,Beautiful Soup會查找與字符串完整匹配的內容,下面的例子用於查找文檔中所有的標籤

>>> soup.find_all('b')
[<b>The Dormouse's story</b>]
>>> 

B.傳正則表達式

如果傳入正則表達式作爲參數,Beautiful Soup會通過正則表達式的 match() 來匹配內容.下面例子中找出所有以b開頭的標籤,這表示和標籤都應該被找到

>>> 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
a
p

E.傳方法

如果沒有合適過濾器,那麼還可以定義一個方法,方法只接受一個元素參數 ,如果這個方法返回 True 表示當前元素匹配並且被找到,如果不是則返回False
下面方法校驗了當前元素,如果包含 class 屬性卻不包含 id 屬性,那麼將返回 True:

def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

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']

4)limit 參數

find_all() 方法返回全部的搜索結構,如果文檔樹很大那麼搜索會很慢.如果我們不需要全部結果,可以使用 limit 參數限制返回結果的數量.效果與SQL中的limit關鍵字類似,當搜索到的結果數量達到 limit 的限制時,就停止搜索返回結果.
文檔樹中有3個tag符合搜索條件,但結果只返回了2個,因爲我們限制了返回數量

5)recursive 參數

調用tag的 find_all() 方法時,Beautiful Soup會檢索當前tag的所有子孫節點,如果只想搜索tag的直接子節點,可以使用參數 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()方法返回第一個符合條件的節點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章