BeautifulSoup入門

BeautifulSoup庫入門

BeautifulSoup庫的理解

BeautifulSoup庫是解析、遍歷、維護”標籤樹”的功能庫

示例代碼:

from bs4 import BeautifulSoup
soup = BeautifulSoup("<html>data</html>","html.parser")#第一參數是html文檔,第二個參數指定parser類型是html.parser
soup2 = BeautifulSoup(open("d://demo.html"),"html.parser")

BeautifulSoup解析器

解析器 使用方法 條件
bs4的html解析器: BeautifulSoup(mk,’html.parser’) 安裝bs4庫
lxml的html解析器: BeautifulSoup(mk,’lxml’) pip install lxml
lxml的xml解析器: BeautifulSoup(mk,’xml’) pip install lxml
html5lib的解析器: BeautifulSoup(mk,’html5lib’) pip install html5lib

BeautifulSoup類的基本元素

基本元素 說明 使用方式
Tag 標籤,最基本的信息組織單元,分別用<>和表明開頭和結尾 soup.a soup.p soup.head soup.title
Name 標籤的名字, \…\<\/p> 的名字是p,格式.name soup.a.name soup.p.name soup.div.name
Attribute 標籤的屬性,字典形式組織,格式: .attrs soup.a.attrs soup.div.attrs
NavigableString 標籤內非屬性字符串,<>中字符串,格式:.string soup.a.string soup.p.string
Comment 標籤內字符串的註釋部分 soup.a.string(會去掉!–和–,只顯示註釋內容,但是用type(soup.a.string)會返回)

使用BeautifulSoup遍歷HTML DOM樹

屬性 說明
.contents 子節點的列表,將說有兒子節點存入列表
.children 子節點的迭代類型,與.contents類似,用於遍歷兒子節點
.descendants 子孫節點的迭代類型,包含所有子孫節點,用於循環遍歷
.parent 節點的父親標籤
.parents 節點所有祖先標籤,用於循環遍歷祖先節點
.next_sibling 返回按照HTML文本順序的下一個平行節點標籤
.previous_sibling 返回按照HTML文本順序的上一個平行節點標籤
.next_siblings 迭代類型,返回按照HTML文本順序的後續所有平行節點標籤
.previous_siblings 迭代類型,返回按照HTML文本順序的前續所有平行節點標籤

實例代碼:

from bs4 import BeautifulSoup
import requests
response = requests.get("http://www.icourse163.org/learn/BIT-1001870001")
html = response.text
soup = BeautifulSoup(html,"html.parser")
tag = soup.a
print(tag.contents)#打印子節點列表
for child in tag.children:#迭代所有子節點
    print(child)
for descendant in tag.descendants:#迭代所有子孫節點
    print(descendant
print(tag.parent)#打印父親節點
for parent in tag.parents:#迭代所有父節點
    print(parent)
print(tag.next_sibling)#下一個兄弟節點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章