python3 Beautifulsoup爬蟲必備技能

BeautifulSoup4是爬蟲必學的技能。BeautifulSoup最主要的功能是從網頁抓取數據,Beautiful Soup自動將輸入文檔轉換爲Unicode編碼,
輸出文檔轉換爲utf-8編碼。BeautifulSoup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,如果我們不安裝它,
則 Python 會使用 Python默認的解析器,lxml 解析器更加強大,速度更快,推薦使用lxml 解析器。

一、BeautifulSoup4簡介

BeautifulSoup4和 lxml 一樣,Beautiful Soup 也是一個HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 數據。

BeautifulSoup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,如果我們不安裝它,則 Python 會使用 Python默認的解析器,lxml 解析器更加強大,速度更快,推薦使用lxml 解析器。

Beautiful Soup自動將輸入文檔轉換爲Unicode編碼,輸出文檔轉換爲utf-8編碼。你不需要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。然後,你僅僅需要說明一下原始編碼方式就可以了。

 

二、BeautifulSoup4主要解析器,以及優缺點:

在這裏插入圖片描述

三、BeautifulSoup4簡單使用

記得先安裝 pip3 install beautifulsoup4

假設有這樣一個Html,具體內容如下:

<!DOCTYPE html>
<html>

<head>
    <meta content="text/html;charset=utf-8" http-equiv="content-type" />
    <meta content="IE=Edge" http-equiv="X-UA-Compatible" />
    <meta content="always" name="referrer" />
    <link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css" />
    <title>百度一下,你就知道 </title>
</head>

<body link="#0000cc">
  <div id="wrapper">
    <div id="head">
        <div class="head_wrapper">
          <div id="u1">
            <a class="mnav" href="http://news.baidu.com" name="tj_trnews">新聞 </a>
            <a class="mnav" href="https://www.hao123.com" name="tj_trhao123">hao123 </a>
            <a class="mnav" href="http://map.baidu.com" name="tj_trmap">地圖 </a>
            <a class="mnav" href="http://v.baidu.com" name="tj_trvideo">視頻 </a>
            <a class="mnav" href="http://tieba.baidu.com" name="tj_trtieba">貼吧 </a>
            <a class="bri" href="//www.baidu.com/more/" name="tj_briicon" style="display: block;">更多產品 </a>
          </div>
        </div>
    </div>
  </div>
</body>

</html>

創建beautifulsoup4對象:

from bs4 import BeautifulSoup 
file = open('./aa.html', 'rb') 
html = file.read() 
bs = BeautifulSoup(html,"html.parser") # 縮進格式

print(bs.prettify()) # 格式化html結構
print(bs.title) # 獲取title標籤的名稱
print(bs.title.name) # 獲取title標籤的文本內容
print(bs.title.string) # 獲取head標籤的所有內容
print(bs.head) # 獲取第一個div標籤中的所有內容
print(bs.div) # 獲取第一個div標籤的id的值
print(bs.div["id"]) # 獲取第一個a標籤中的所有內容
print(bs.a) # 獲取所有的a標籤中的所有內容
print(bs.find_all("a")) # 獲取id="u1"
print(bs.find(id="u1")) # 獲取所有的a標籤,並遍歷打印a標籤中的href的值

for item in bs.find_all("a"): 
    print(item.get("href")) # 獲取所有的a標籤,並遍歷打印a標籤的文本值

for item in bs.find_all("a"): 
    print(item.get_text())

 

四、BeautifulSoup4四大對象種類

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

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

4.1、Tag

Tag通俗點講就是HTML中的一個個標籤,例如:

from bs4 import BeautifulSoup 
file = open('./aa.html', 'rb') 
html = file.read() 
bs = BeautifulSoup(html,"html.parser") 

# 獲取title標籤的所有內容
print(bs.title) 

# 獲取head標籤的所有內容
print(bs.head) 

# 獲取第一個a標籤的所有內容
print(bs.a) 

# 類型
print(type(bs.a))

我們可以利用 soup 加標籤名輕鬆地獲取這些標籤的內容,這些對象的類型是bs4.element.Tag。但是注意,它查找的是在所有內容中的第一個符合要求的標籤。

對於 Tag,它有兩個重要的屬性,是 name 和 attrs:

from bs4 import BeautifulSoup 
file = open('./aa.html', 'rb') 
html = file.read() 
bs = BeautifulSoup(html,"html.parser") 

# [document] #bs 對象本身比較特殊,它的 name 即爲 [document]
print(bs.name) 

# head #對於其他內部標籤,輸出的值便爲標籤本身的名稱
print(bs.head.name) 

# 在這裏,我們把 a 標籤的所有屬性打印輸出了出來,得到的類型是一個字典。
print(bs.a.attrs) 

#還可以利用get方法,傳入屬性的名稱,二者是等價的
print(bs.a['class']) # 等價 bs.a.get('class')

# 可以對這些屬性和內容等等進行修改
bs.a['class'] = "newClass"
print(bs.a) 

# 還可以對這個屬性進行刪除
del bs.a['class'] 
print(bs.a)

 

4.2、NavigableString

既然我們已經得到了標籤的內容,那麼問題來了,我們要想獲取標籤內部的文字怎麼辦呢?很簡單,用 .string 即可,例如:

from bs4 import BeautifulSoup 
file = open('./aa.html', 'rb') 
html = file.read() 

bs = BeautifulSoup(html,"html.parser")
 
print(bs.title.string) 
print(type(bs.title.string))

 

4.3、BeautifulSoup

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

from bs4 import BeautifulSoup 
file = open('./aa.html', 'rb') 
html = file.read()
 
bs = BeautifulSoup(html,"html.parser") 

print(type(bs.name)) 
print(bs.name) 
print(bs.attrs)

 

4.4、Comment

Comment 對象是一個特殊類型的 NavigableString 對象,其輸出的內容不包括註釋符號。

from bs4 import BeautifulSoup 
file = open('./aa.html', 'rb') 
html = file.read() 

bs = BeautifulSoup(html,"html.parser") 
print(bs.a)
# 此時不能出現空格和換行符,a標籤如下:
# <a class="mnav" href="http://news.baidu.com" name="tj_trnews"><!--新聞--></a>

print(bs.a.string) # 新聞

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

 

五、遍歷文檔樹

5.1、.contents:獲取Tag的所有子節點,返回一個list

# tag的.content 屬性可以將tag的子節點以列表的方式輸出
print(bs.head.contents)

# 用列表索引來獲取它的某一個元素
print(bs.head.contents[1])

 

5.2、.children獲取Tag的所有子節點,返回一個生成器

for child in  bs.body.children:
    print(child)

5.3、.descendants:獲取Tag的所有子孫節點

5.4、.strings:如果Tag包含多個字符串,即在子孫節點中有內容,可以用此獲取,而後進行遍歷

5.5、.stripped_strings:與strings用法一致,只不過可以去除掉那些多餘的空白內容

5.6、.parent:獲取Tag的父節點

5.7、.parents:遞歸得到父輩元素的所有節點,返回一個生成器

5.8、.previous_sibling:獲取當前Tag的上一個節點,屬性通常是字符串或空白,真實結果是當前標籤與上一個標籤之間的頓號和換行符

5.9、.next_sibling:獲取當前Tag的下一個節點,屬性通常是字符串或空白,真是結果是當前標籤與下一個標籤之間的頓號與換行符

5.10、.previous_siblings:獲取當前Tag的上面所有的兄弟節點,返回一個生成器

5.11、.next_siblings:獲取當前Tag的下面所有的兄弟節點,返回一個生成器

5.12、.previous_element:獲取解析過程中上一個被解析的對象(字符串或tag),可能與previous_sibling相同,但通常是不一樣的

5.13、.next_element:獲取解析過程中下一個被解析的對象(字符串或tag),可能與next_sibling相同,但通常是不一樣的

5.14、.previous_elements:返回一個生成器,可以向前訪問文檔的解析內容

5.15、.next_elements:返回一個生成器,可以向後訪問文檔的解析內容

5.16、.has_attr:判斷Tag是否包含屬性

 

六、搜索文檔樹

6.1、find_all(name, attrs, recursive, text, **kwargs)

在上面的栗子中我們簡單介紹了find_all的使用,接下來介紹一下find_all的更多用法-過濾器。這些過濾器貫穿整個搜索API,過濾器可以被用在tag的name中,節點的屬性等。

(1)name參數:

字符串過濾:會查找與字符串完全匹配的內容

a_list = bs.find_all("a")
print(a_list)

正則表達式過濾:如果傳入的是正則表達式,那麼BeautifulSoup4會通過search()來匹配內容

from bs4 import BeautifulSoup 
import re 
file = open('./aa.html', 'rb') 
html = file.read() 

bs = BeautifulSoup(html,"html.parser") 

t_list = bs.find_all(re.compile("a")) 
for item in t_list: 
   print(item)

列表:如果傳入一個列表,BeautifulSoup4將會與列表中的任一元素匹配到的節點返回

t_list = bs.find_all(["meta","link"])
for item in t_list:
    print(item)

方法:傳入一個方法,根據方法來匹配

from bs4 import BeautifulSoup 
file = open('./aa.html', 'rb') 
html = file.read() 

bs = BeautifulSoup(html,"html.parser") 

def name_is_exists(tag): 
    return tag.has_attr("name") 

t_list = bs.find_all(name_is_exists) 
for item in t_list: 
    print(item)

 

(2)kwargs參數:

from bs4 import BeautifulSoup 
import re 
file = open('./aa.html', 'rb') 
html = file.read() 

bs = BeautifulSoup(html,"html.parser") 

# 查詢id=head的Tag
t_list = bs.find_all(id="head") print(t_list) 

# 查詢href屬性包含ss1.bdstatic.com的Tag
t_list = bs.find_all(href=re.compile("http://news.baidu.com")) 
print(t_list) 

# 查詢所有包含class的Tag(注意:class在Python中屬於關鍵字,所以加_以示區別)
t_list = bs.find_all(class_=True) 
for item in t_list: 
    print(item)

 

(3)attrs參數:

並不是所有的屬性都可以使用上面這種方式進行搜索,比如HTML的data-*屬性:

t_list = bs.find_all(data-foo="value")

如果執行這段代碼,將會報錯。我們可以使用attrs參數,定義一個字典來搜索包含特殊屬性的tag:

t_list = bs.find_all(attrs={"data-foo":"value"})
for item in t_list:
    print(item)

(4)text參數:

通過text參數可以搜索文檔中的字符串內容,與name參數的可選值一樣,text參數接受 字符串,正則表達式,列表

from bs4 import BeautifulSoup 
import re 
file = open('./aa.html', 'rb') 
html = file.read() 

bs = BeautifulSoup(html, "html.parser") 

t_list = bs.find_all(attrs={"data-foo": "value"}) 
for item in t_list: 
    print(item) 

t_list = bs.find_all(text="hao123") 
for item in t_list: 
    print(item) 

t_list = bs.find_all(text=["hao123", "地圖", "貼吧"]) 
for item in t_list: 
    print(item) 

t_list = bs.find_all(text=re.compile("\d")) 
for item in t_list: 
    print(item)

當我們搜索text中的一些特殊屬性時,同樣也可以傳入一個方法來達到我們的目的:

def length_is_two(text):
    return text and len(text) == 2

t_list = bs.find_all(text=length_is_two)
for item in t_list:
    print(item)

(5)limit參數:

可以傳入一個limit參數來限制返回的數量,當搜索出的數據量爲5,而設置了limit=2時,此時只會返回前2個數據

from bs4 import BeautifulSoup 
import re 
file = open('./aa.html', 'rb') 
html = file.read() 

bs = BeautifulSoup(html, "html.parser") 

t_list = bs.find_all("a",limit=2) 
for item in t_list: 
    print(item)

find_all除了上面一些常規的寫法,還可以對其進行一些簡寫:

# 兩者是相等的
# t_list = bs.find_all("a") => t_list = bs("a")
t_list = bs("a") # 兩者是相等的
# t_list = bs.a.find_all(text="新聞") => t_list = bs.a(text="新聞")
t_list = bs.a(text="新聞")

 

6.2、find()

find()將返回符合條件的第一個Tag,有時我們只需要或一個Tag時,我們就可以用到find()方法了。當然了,也可以使用find_all()方法,傳入一個limit=1,然後再取出第一個值也是可以的,不過未免繁瑣。

from bs4 import BeautifulSoup 
import re 
file = open('./aa.html', 'rb') 
html = file.read() 

bs = BeautifulSoup(html, "html.parser") 

# 返回只有一個結果的列表
t_list = bs.find_all("title",limit=1) 
print(t_list) 

# 返回唯一值
t = bs.find("title") 
print(t) 

# 如果沒有找到,則返回None
t = bs.find("abc") print(t)

從結果可以看出find_all,儘管傳入了limit=1,但是返回值仍然爲一個列表,當我們只需要取一個值時,遠不如find方法方便。但

是如果未搜索到值時,將返回一個None

 

在上面介紹BeautifulSoup4的時候,我們知道可以通過bs.div來獲取第一個div標籤,如果我們需要獲取第一個div下的第一個div,

我們可以這樣:

t = bs.div.div

# 等價於
t = bs.find("div").find("div")

 

七、CSS選擇器

BeautifulSoup支持發部分的CSS選擇器,在Tag獲取BeautifulSoup對象的.select()方法中傳入字符串參數,即可使用CSS選擇器的語法找到Tag:

7.1、通過標籤名查找

print(bs.select('title'))

print(bs.select('a'))

7.2、通過類名查找

print(bs.select('.mnav'))

7.3、通過id查找

print(bs.select('#u1'))

7.4、組合查找

print(bs.select('div .bri'))

7.5、屬性查找

print(bs.select('a[class="bri"]'))
print(bs.select('a[href="http://tieba.baidu.com"]'))

7.6、直接子標籤查找

t_list = bs.select("head > title")
print(t_list)

7.7、兄弟節點標籤查找

t_list = bs.select(".mnav ~ .bri")
print(t_list)

7.8、獲取內容

t_list = bs.select("title")
print(bs.select('title')[0].get_text())

 

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