當前位置:網站首頁>BeautifulSoup 學習筆記
BeautifulSoup 學習筆記
2022-01-26 23:43:38 【靠譜的人】
BeautifulSoup學習筆記
1.基礎介紹
GitHub地址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
Beautiful Soup 是一個可以從HTML或XML文件中提取數據的Python庫.它能够通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.Beautiful Soup會幫你節省數小時甚至數天的工作時間.
按照github舉得例子我們也按照那個分析一下,分析對象命名為html_doc,內容是一段html代碼,正常情况下,我們解析的是response.content.decode(‘utf-8’)
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>
"""
2.解析並按標准格式輸出
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
3.幾個快速瀏覽的方法
# <title>The Dormouse's story</title>
soup.title.name
# u'title'
soup.title.string
# u'The Dormouse's story'
soup.title.parent.name
# u'head'
soup.p
# <p class="title"><b>The Dormouse's story</b></p>
soup.p['class']
# u'title'
soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
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>,
# # <title>The Dormouse's story</title>
soup.title.name
# u'title'
soup.title.string
# u'The Dormouse's story'
soup.title.parent.name
# u'head'
soup.p
# <p class="title"><b>The Dormouse's story</b></p>
soup.p['class']
# u'title'
soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
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>]
soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
以上都是通過soup.標簽名字,快速瀏覽標簽,應用很局限,下面我們來深入探討一下。
4.對象的種類
Beautiful Soup將複雜HTML文檔轉換成一個複雜的樹形結構,每個節點都是Python對象,所有對象可以歸納為4種: Tag , NavigableString , BeautifulSoup , Comment .
Tag標簽
html的基礎就是Tag標簽 如
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
就是一個Tag標簽,Tag有很多方法和屬性,在 遍曆文檔樹 和 搜索文檔樹 中有詳細解釋.現在介紹一下tag中最重要的屬性: name和attributes。
Name
每個tag都有自己的名字,通過 .name 來獲取:
如上例 soup.a.name 結果當然是 a 了,因為他是個 a 標簽嘛,貌似這個沒啥用,後邊配合樹遍曆的時候才能看出應用。
Attributes
一個tag可能有很多個屬性. tag 有一個 “class” 的屬性,值為 “boldest” . tag的屬性的操作方法與字典相同:可以有三種
soup.a['class']
soup.a.get('class')
soup.a.attrs['class']
在說一遍,Tag的屬性操作方法與字典相同!!!
NavigableString 字符串
Beautiful Soup用 NavigableString 類來包裝tag中的字符串,操作的時候使用tag.string
soup.a.string //結果是 Elise
如果想要一次性獲取所有標簽的字符串,使用.text,相當於加强版的.string對於爬小說很有用哦!
一個 NavigableString 字符串與Python中的Unicode字符串相同,並且還支持包含在 遍曆文檔樹 和 搜索文檔樹 中的一些特性. 通過 unicode() 方法可以直接將 NavigableString 對象轉換成Unicode字符串:
unicode_string = unicode(tag.string)
unicode_string
# u'Extremely bold'
type(unicode_string)
# <type 'unicode'>
tag中包含的字符串不能編輯,但是可以被替換成其它的字符串,用 replace_with() 方法:
tag.string.replace_with("No longer bold")
tag
# <blockquote>No longer bold</blockquote>
NavigableString 對象支持 遍曆文檔樹 和 搜索文檔樹 中定義的大部分屬性, 並非全部.尤其是,一個字符串不能包含其它內容(tag能够包含字符串或是其它tag),字符串不支持 .contents 或 .string 屬性或 find() 方法.
如果想在Beautiful Soup之外使用 NavigableString 對象,需要調用 unicode() 方法,將該對象轉換成普通的Unicode字符串,否則就算Beautiful Soup已方法已經執行結束,該對象的輸出也會帶有對象的引用地址.這樣會浪費內存.
BeautifulSoup 對象
BeautifulSoup 對象錶示的是一個文檔的全部內容.大部分時候,可以把它當作 Tag 對象,它支持 遍曆文檔樹 和 搜索文檔樹 中描述的大部分的方法.
因為 BeautifulSoup 對象並不是真正的HTML或XML的tag,所以它沒有name和attribute屬性.但有時查看它的 .name 屬性是很方便的,所以 BeautifulSoup 對象包含了一個值為 “[document]” 的特殊屬性 .name
、
注釋 Comment
Tag , NavigableString , BeautifulSoup 幾乎覆蓋了html和xml中的所有內容,但是還有一些特殊對象.容易讓人擔心的內容是文檔的注釋部分:
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(markup)
comment = soup.b.string
type(comment)
# <class 'bs4.element.Comment'>
Comment 對象是一個特殊類型的 NavigableString 對象:
comment
# u'Hey, buddy. Want to buy a used parser'
5.一些使用操作
獲取所有a標簽的文字內容
兩種方法
soup = BeautifulSoup(html_doc, 'html.parser')
strs = soup.find_all('a')
for str in strs:
print(str.string)
soup = BeautifulSoup(html_doc, 'html.parser')
strs = soup.find_all('a')
for str in strs:
print(list(str.strings)[0])
第一種很容易理解,這個例子比較簡單,如果標簽嵌套很多的話,第二種就比較簡單了,str.strings是直接獲取所有標簽的文字內容,但結果是一個生成器,就需要用list()方法轉換成一個列錶,再取內容。不理解的話,多操作幾次就明白了。
類似的還有
版權聲明
本文為[靠譜的人]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/01/202201262343376411.html
邊欄推薦
猜你喜歡
隨機推薦
- MySQL-5.7.36安裝遇到坑之後的整理,刻入骨髓的1045
- leader epoch
- 圖的著色問題
- Wireshark實驗四:UDP
- 面試面到自閉,職場反思,原來是我沒有掌握其中精髓
- 遞歸以及for循環裏async 和 await 的用法
- 大人重疾險想保終身重疾,買哪個產品最合適啊?
- php使用openssl_encrypt和openssl_decrypt進行AES加密解密
- CV in Transformer學習筆記(持續更新)
- ctf,show msic入門
- 網絡文件系統
- Js基礎_作用域
- 《滲透測試具體流程》
- flask入門教程(7) - 會話
- 【電子技術】什麼是循環冗餘碼CRC
- Endnote使用方法——檢查參考文獻
- Anconda 學習
- LeetCode 7.整數反轉
- 【ISO15765_UDS&OBD診斷】-02-Network layer網絡層介紹
- C 練習實例90
- 小程序雲開發——雲數據庫的增删查改(2)
- 五、OpenGL ES 三維圖形的初探
- 適合10歲小孩投保的保險產品都有什麼啊?少兒險可以買哪些險種?
- Material Design 3 全新的進階版本UI庫
- 登錄令牌JWT — JSON WEB TOKEN
- Leetcode 算法面試沖刺 實戰 五(數組與循環)(十二)
- 兩種方法,word文件轉換成PDF文件
- 有符號數(signed) 和 無符號數(unsigned)
- [機器學習算法面試題] 一.准確率Accuracy的局限性
- String類常用方法示例
- 各大直播平臺主播的收入計算方式是怎樣的?
- 工程師必須知道的幾個原則
- 細品事務機制(一)
- 邏輯樹分析方法:如何將複雜問題變簡單?
- DCGAN 源碼解析
- 李宏毅《機器學習》| 神經網絡訓練不起來怎麼辦(下)
- 2021年P氣瓶充裝考試及P氣瓶充裝試題及解析
- 2021年G2電站鍋爐司爐考試題庫及G2電站鍋爐司爐考試試卷
- Go 自定義日期時間格式解析解决方案 - 解决 `parsing time xx as xx: cannot parse xx as xx` 錯誤
- 『淺入淺出』MySQL 和 InnoDB