Beautifulsoup模塊

来源:https://www.cnblogs.com/ctztake/archive/2018/01/19/8318393.html
-Advertisement-
Play Games

Beautifulsoup模塊 一 介紹 Beautiful Soup 是一個可以從HTML或XML文件中提取數據的Python庫.它能夠通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.Beautiful Soup會幫你節省數小時甚至數天的工作時間.你可能在尋找 Beautiful So ...


Beautifulsoup模塊

一 介紹

Beautiful Soup 是一個可以從HTML或XML文件中提取數據的Python庫.它能夠通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.Beautiful Soup會幫你節省數小時甚至數天的工作時間.你可能在尋找 Beautiful Soup3 的文檔,Beautiful Soup 3 目前已經停止開發,官網推薦在現在的項目中使用Beautiful Soup 4, 移植到BS4

#安裝 Beautiful Soup
pip install beautifulsoup4

#安裝解析器
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

下表列出了主要的解析器,以及它們的優缺點,官網推薦使用lxml作為解析器,因為效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必須安裝lxml或html5lib, 因為那些Python版本的標準庫中內置的HTML解析方法不夠穩定.

解析器使用方法優勢劣勢
Python標準庫 BeautifulSoup(markup, "html.parser")
  • Python的內置標準庫
  • 執行速度適中
  • 文檔容錯能力強
  • Python 2.7.3 or 3.2.2)前 的版本中文檔容錯能力差
lxml HTML 解析器 BeautifulSoup(markup, "lxml")
  • 速度快
  • 文檔容錯能力強
  • 需要安裝C語言庫
lxml XML 解析器

BeautifulSoup(markup, ["lxml", "xml"])

BeautifulSoup(markup, "xml")

  • 速度快
  • 唯一支持XML的解析器
  • 需要安裝C語言庫
html5lib BeautifulSoup(markup, "html5lib")
  • 最好的容錯性
  • 以瀏覽器的方式解析文檔
  • 生成HTML5格式的文檔
  • 速度慢
  • 不依賴外部擴展

中文文檔:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

二 基本使用

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

#基本使用:容錯處理,文檔的容錯能力指的是在html代碼不完整的情況下,使用該模塊可以識別該錯誤。使用BeautifulSoup解析上述代碼,能夠得到一個 BeautifulSoup 的對象,並能按照標準的縮進格式的結構輸出
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml') #具有容錯功能
res=soup.prettify() #處理好縮進,結構化顯示
print(res)

三 遍歷文檔樹

#遍歷文檔樹:即直接通過標簽名字選擇,特點是選擇速度快,但如果存在多個相同的標簽則只返回第一個
#1、用法
#2、獲取標簽的名稱
#3、獲取標簽的屬性
#4、獲取標簽的內容
#5、嵌套選擇
#6、子節點、子孫節點
#7、父節點、祖先節點
#8、兄弟節點
#遍歷文檔樹:即直接通過標簽名字選擇,特點是選擇速度快,但如果存在多個相同的標簽則只返回第一個
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title"><b id="bbb" class="boldest">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>
"""

#1、用法
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml')
# soup=BeautifulSoup(open('a.html'),'lxml')

print(soup.p) #存在多個相同的標簽則只返回第一個
print(soup.a) #存在多個相同的標簽則只返回第一個

#2、獲取標簽的名稱
print(soup.p.name)

#3、獲取標簽的屬性
print(soup.p.attrs)

#4、獲取標簽的內容
print(soup.p.string) # p下的文本只有一個時,取到,否則為None
print(soup.p.strings) #拿到一個生成器對象, 取到p下所有的文本內容
print(soup.p.text) #取到p下所有的文本內容
for line in soup.stripped_strings: #去掉空白
    print(line)


'''
如果tag包含了多個子節點,tag就無法確定 .string 方法應該調用哪個子節點的內容, .string 的輸出結果是 None,如果只有一個子節點那麼就輸出該子節點的文本,比如下麵的這種結構,soup.p.string 返回為None,但soup.p.strings就可以找到所有文本
<p id='list-1'>
    哈哈哈哈
    <a class='sss'>
        <span>
            <h1>aaaa</h1>
        </span>
    </a>
    <b>bbbbb</b>
</p>
'''

#5、嵌套選擇
print(soup.head.title.string)
print(soup.body.a.string)


#6、子節點、子孫節點
print(soup.p.contents) #p下所有子節點
print(soup.p.children) #得到一個迭代器,包含p下所有子節點

for i,child in enumerate(soup.p.children):
    print(i,child)

print(soup.p.descendants) #獲取子孫節點,p下所有的標簽都會選擇出來
for i,child in enumerate(soup.p.descendants):
    print(i,child)

#7、父節點、祖先節點
print(soup.a.parent) #獲取a標簽的父節點
print(soup.a.parents) #找到a標簽所有的祖先節點,父親的父親,父親的父親的父親...


#8、兄弟節點
print('=====>')
print(soup.a.next_sibling) #下一個兄弟
print(soup.a.previous_sibling) #上一個兄弟

print(list(soup.a.next_siblings)) #下麵的兄弟們=>生成器對象
print(soup.a.previous_siblings) #上面的兄弟們=>生成器對象
View Code

四 搜索文檔樹

1、五種過濾器

#搜索文檔樹:BeautifulSoup定義了很多搜索方法,這裡著重介紹2個: find() 和 find_all() .其它方法的參數和用法類似
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title"><b id="bbb" class="boldest">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')

#1、五種過濾器: 字元串、正則表達式、列表、True、方法
#1.1、字元串:即標簽名
print(soup.find_all('b'))

#1.2、正則表達式
import re
print(soup.find_all(re.compile('^b'))) #找出b開頭的標簽,結果有body和b標簽

#1.3、列表:如果傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回.下麵代碼找到文檔中所有<a>標簽和<b>標簽:
print(soup.find_all(['a','b']))

#1.4、True:可以匹配任何值,下麵代碼查找到所有的tag,但是不會返回字元串節點
print(soup.find_all(True))
for tag in soup.find_all(True):
    print(tag.name)

#1.5、方法:如果沒有合適過濾器,那麼還可以定義一個方法,方法只接受一個元素參數 ,如果這個方法返回 True 表示當前元素匹配並且被找到,如果不是則反回 False
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

print(soup.find_all(has_class_but_no_id))
View Code

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

#2、find_all( name , attrs , recursive , text , **kwargs )
#2.1、name: 搜索name參數的值可以使任一類型的 過濾器 ,字元竄,正則表達式,列表,方法或是 True .
print(soup.find_all(name=re.compile('^t')))

#2.2、keyword: key=value的形式,value可以是過濾器:字元串 , 正則表達式 , 列表, True .
print(soup.find_all(id=re.compile('my')))
print(soup.find_all(href=re.compile('lacie'),id=re.compile('\d'))) #註意類要用class_
print(soup.find_all(id=True)) #查找有id屬性的標簽

# 有些tag屬性在搜索不能使用,比如HTML5中的 data-* 屬性:
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>','lxml')
# data_soup.find_all(data-foo="value") #報錯:SyntaxError: keyword can't be an expression
# 但是可以通過 find_all() 方法的 attrs 參數定義一個字典參數來搜索包含特殊屬性的tag:
print(data_soup.find_all(attrs={"data-foo": "value"}))
# [<div data-foo="value">foo!</div>]

#2.3、按照類名查找,註意關鍵字是class_,class_=value,value可以是五種選擇器之一
print(soup.find_all('a',class_='sister')) #查找類為sister的a標簽
print(soup.find_all('a',class_='sister ssss')) #查找類為sister和sss的a標簽,順序錯誤也匹配不成功
print(soup.find_all(class_=re.compile('^sis'))) #查找類為sister的所有標簽

#2.4、attrs
print(soup.find_all('p',attrs={'class':'story'}))

#2.5、text: 值可以是:字元,列表,True,正則
print(soup.find_all(text='Elsie'))
print(soup.find_all('a',text='Elsie'))

#2.6、limit參數:如果文檔樹很大那麼搜索會很慢.如果我們不需要全部結果,可以使用 limit 參數限制返回結果的數量.效果與SQL中的limit關鍵字類似,當搜索到的結果數量達到 limit 的限制時,就停止搜索返回結果
print(soup.find_all('a',limit=2))

#2.7、recursive:調用tag的 find_all() 方法時,Beautiful Soup會檢索當前tag的所有子孫節點,如果只想搜索tag的直接子節點,可以使用參數 recursive=False .
print(soup.html.find_all('a'))
print(soup.html.find_all('a',recursive=False))

'''
像調用 find_all() 一樣調用tag
find_all() 幾乎是Beautiful Soup中最常用的搜索方法,所以我們定義了它的簡寫方法. BeautifulSoup 對象和 tag 對象可以被當作一個方法來使用,這個方法的執行結果與調用這個對象的 find_all() 方法相同,下麵兩行代碼是等價的:
soup.find_all("a")
soup("a")
這兩行代碼也是等價的:
soup.title.find_all(text=True)
soup.title(text=True)
'''
View Code

3、find( name , attrs , recursive , text , **kwargs )

#3、find( name , attrs , recursive , text , **kwargs )
find_all() 方法將返迴文檔中符合條件的所有tag,儘管有時候我們只想得到一個結果.比如文檔中只有一個<body>標簽,那麼使用 find_all() 方法來查找<body>標簽就不太合適, 使用 find_all 方法並設置 limit=1 參數不如直接使用 find() 方法.下麵兩行代碼是等價的:

soup.find_all('title', limit=1)
# [<title>The Dormouse's story</title>]
soup.find('title')
# <title>The Dormouse's story</title>

唯一的區別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回結果.
find_all() 方法沒有找到目標是返回空列表, find() 方法找不到目標時,返回 None .
print(soup.find("nosuchtag"))
# None

soup.head.title 是 tag的名字 方法的簡寫.這個簡寫的原理就是多次調用當前tag的 find() 方法:

soup.head.title
# <title>The Dormouse's story</title>
soup.find("head").find("title")
# <title>The Dormouse's story</title>
View Code

4、其他方法

#見官網:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find-parents-find-parent
View Code

5、CSS選擇器

#該模塊提供了select方法來支持css,詳見官網:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id37
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title">
    <b>The Dormouse's story</b>
    Once upon a time there were three little sisters; and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">
        <span>Elsie</span>
    </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>;
    <div class='panel-1'>
        <ul class='list' id='list-1'>
            <li class='element'>Foo</li>
            <li class='element'>Bar</li>
            <li class='element'>Jay</li>
        </ul>
        <ul class='list list-small' id='list-2'>
            <li class='element'><h1 class='yyyy'>Foo</h1></li>
            <li class='element xxx'>Bar</li>
            <li class='element'>Jay</li>
        </ul>
    </div>
    and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml')

#1、CSS選擇器
print(soup.p.select('.sister'))
print(soup.select('.sister span'))

print(soup.select('#link1'))
print(soup.select('#link1 span'))

print(soup.select('#list-2 .element.xxx'))

print(soup.select('#list-2')[0].select('.element')) #可以一直select,但其實沒必要,一條select就可以了

# 2、獲取屬性
print(soup.select('#list-2 h1')[0].attrs)

# 3、獲取內容
print(soup.select('#list-2 h1')[0].get_text())
View Code

五 修改文檔樹

鏈接:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id40

六 總結

# 總結:
#1、推薦使用lxml解析庫
#2、講了三種選擇器:標簽選擇器,find與find_all,css選擇器
    1、標簽選擇器篩選功能弱,但是速度快
    2、建議使用find,find_all查詢匹配單個結果或者多個結果
    3、如果對css選擇器非常熟悉建議使用select
#3、記住常用的獲取屬性attrs和文本值get_text()的方法

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • typedef 是C語言提供的一種高級數據特性,它能幫助我們給某一類型創建我們自己的名字,方便我們編碼和使用。 ...
  • 昨天我們使用了dlib和opencv進行了人臉檢測標註(http://www.cnblogs.com/take-fetter/p/8310298.html) 但是運行環境是基於windows的而且可能因為我的電腦上的visual studio配置比較完備,安裝運行沒有出現任何問題. 因為之後我打算把 ...
  • 迭代器 可迭代對象:可迭代對象實現了__iter__方法,該方法返回一個迭代器對象。 迭代器: 那麼什麼迭代器呢?它是一個帶狀態的對象,他能在你調用next()方法的時候返回容器中的下一個值,任何實現了__iter__和__next__(python2中實現next())方法的對象都是迭代器,__i ...
  • 辛苦Mark的 Google公司關於Python的風格規範,emmm~ ...
  • 1. 安裝mysql-python 運行下麵的命令: 安裝以後: 如果沒有出錯,就表明安裝成功。 2. 連接MySQL 其中localhost是伺服器名,root是用戶名,1是密碼,fs是資料庫名稱,前提是MySQL資料庫設置了相應的用戶名和密碼。 連接成功以後,通過 獲取游標。 3. 查詢數據 c ...
  • ****************************************************************************************** excel表格導出,使用POI實現 ***************************************** ...
  • 一、簡介 MongoDB是一款強大、靈活、且易於擴展的通用型資料庫 1、易用性 2、易擴展性 3、豐富的功能 4、卓越的性能 二、MongoDB基礎 a、文檔是MongoDB的核心概念。文檔就是鍵值對的一個有序集{'msg':'hello','foo':3}。類似於python中的有序字典 b、集合 ...
  • 因為有基礎,我直接簡單寫了##定義類,創建對象,調用對象方法,返回值 ##添加屬性,和Java有區別 ##構造方法 python構造方法只有一個或者沒有,和Java不同 ###繼承 1 class Father: 2 def f(self): 3 print('father') 4 def smok ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...