《Python網絡爬蟲與信息提取》第二週 網絡爬蟲之提取 學習筆記(一)Beautiful Soup庫入門

目錄

一、Beautiful Soup庫入門

1、Beautiful Soup庫入門

(1)Beautiful Soup庫的定義

(2)Beautiful Soup庫的官網

(3)Beautiful Soup庫的安裝

(4)Beautiful Soup庫的安裝小測

2、Beautiful Soup庫的基本元素

(1)Beautiful Soup庫的理解

(2)Beautiful Soup庫的引用

(3)Beautiful Soup類

(4)Beautiful Soup庫解析器

(5)Beautiful Soup類的基本元素

3、基於bs4庫的HTML內容遍歷方法

(1)回顧demo.html

(2)HTML基本格式

(3)標籤樹的遍歷方式

4、基於bs4庫的HTML格式輸出

(1)bs4庫的prettify()方法

(2)bs4庫的編碼


一、Beautiful Soup庫入門

1、Beautiful Soup庫入門

(1)Beautiful Soup庫的定義

解析HTML頁面信息標記與提取方法。

(2)Beautiful Soup庫的官網

https://www.crummy.com/software/BeautifulSoup/

(3)Beautiful Soup庫的安裝

管理員權限啓動cmd。

輸入:

pip install beautifulsoup4

備註:直接安裝Anaconda,更加方便。(https://blog.csdn.net/wyatt007/article/details/80369755) 

(4)Beautiful Soup庫的安裝小測

演示HTML頁面地址:https://python123.io/ws/demo.html

頁面源代碼:HTML5.0格式代碼。

<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>
</body></html>
# Beautiful Soup庫的安裝小測
from bs4 import BeautifulSoup

soup = BeautifulSoup('<p>data</p>', "html.parser")  # BeautifulSoup是一個類,第一個參數是需要BeautifulSoup解析的html信息,第二個參數是需要用的解析器。

# Beautiful Soup庫的安裝小測全代碼
import requests

r = requests.get("http://python123.io/ws/demo.html")
r.text
print(r.text)
demo = r.text

from bs4 import BeautifulSoup

soup = BeautifulSoup(demo, "html.parser")
print(soup.prettify())

2、Beautiful Soup庫的基本元素

(1)Beautiful Soup庫的理解

Beautiful Soup庫是解析、遍歷、維護“標籤樹”的功能庫。

<html>
    <body>
        <p class="title"> ... </p>
    </body>
</html>

①<p>...</p>:標籤(Tag)。

②p:名稱Name成對出現。

③class="title":屬性(Attributes)0個或多個。

(2)Beautiful Soup庫的引用

Beautiful Soup庫,也叫beautifulsoup4或bs4。

from bs4 import BeautifulSoup

或者 

import bs4

(3)Beautiful Soup類

HTML文檔↔標籤樹↔BeautifulSoup類。

備註:“↔”表示等價關係。

# Beautiful Soup類
from bs4 import BeautifulSoup

soup = BeautifulSoup('<p>data</p>', 'html.parser')
soup2 = BeautifulSoup(open("H://python//Web Crawler//demo.html"), "html.parser")  # 打開一個html文件。

備註:soup2的html文件路徑請讀者自己配置。

BeautifulSoup對應一個HTML/XML文檔的全部內容。

(4)Beautiful Soup庫解析器

解析器 使用方法 條件
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

(5)Beautiful Soup類的基本元素

基本元素 說明
Tag 標籤,最基本的信息組織單元,分別用<>和</>標明開頭和結尾
Name 標籤的名字,<p>...</p>的名字是'p',格式:<tag>.name
Attributes 標籤的屬性,字典形式組織,格式:<tag>.attrs
NavigableString 標籤內非屬性字符串,<>...</>中字符串,格式:<tag>.string
Comment 標籤內字符串的註釋部分,一種特殊的Comment類型

回顧demo.html:

演示HTML頁面地址:https://python123.io/ws/demo.html

①標籤(Tag):任何存在於HTML語法中的標籤都可以用soup.<tag>訪問獲得,當HTML文檔中存在多個相同<tag>對應內容時,soup.<tag>返回第一個。

②標籤的名字(Name):每個<tag>都有自己的名字,通過<tag>.name獲取,字符串類型。

③標籤的屬性(Attributes):一個<tag>可以有0或多個屬性,字典類型。

④標籤內非屬性字符串(NavigableString):NavigableString可以跨越多個層次。

⑤標籤內字符串的註釋部分(Comment):Comment是一種特殊類型。

# Beautiful Soup類的基本元素
# 標籤(Tag)
import requests

r = requests.get("http://python123.io/ws/demo.html")
demo = r.text

from bs4 import BeautifulSoup

soup = BeautifulSoup(demo, 'html.parser')
soup.title
print(soup.title)
tag = soup.a
tag
print(tag)

# 標籤的名字(Name)
soup.a.name
print(soup.a.name)
soup.a.parent.name
print(soup.a.parent.name)
soup.a.parent.parent.name
print(soup.a.parent.parent.name)

# 標籤的屬性(Attributes)
tag = soup.a
tag.attrs
print(tag.attrs)
tag.attrs['class']
print(tag.attrs['class'])
tag.attrs['href']
print(tag.attrs['href'])
type(tag.attrs)
print(type(tag.attrs))
type(tag)
print(type(tag))

# 標籤內非屬性字符串(NavigableString)
soup.a
print(soup.a)
soup.a.string
print(soup.a.string)
soup.p
print(soup.p)
soup.p.string
print(soup.p.string)
type(soup.p.string)
print(type(soup.p.string))

# 標籤內字符串的註釋部分(Comment)
newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</p>", "html.parser")
newsoup.b.string
print(newsoup.b.string)
type(newsoup.b.string)
print(type(newsoup.b.string))
newsoup.p.string
print(newsoup.p.string)
type(newsoup.p.string)
print(type(newsoup.p.string))

小結:

<p class="title"> ... </p>

①<p class="title">:標籤.<tag>。

②p:名稱.Name。

③class="title":屬性.attrs。

④...:非屬性字符串/註釋.string。

3、基於bs4庫的HTML內容遍歷方法

(1)回顧demo.html

# 回顧demo.html
import requests

r = requests.get("http://python123.io/ws/demo.html")
demo = r.text

(2)HTML基本格式

<html>
    <head>
        <title>This is a python demo page</title>
    </head>
    <body>
        <p class="title">
            <b>The demo python introduces several python courses.</b>
        </p>
        <p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
            <a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and 
            <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.
        </p>
    </body>
</html>

(3)標籤樹的遍歷方式

html或者xml都是樹形結構。

三種遍歷方式:下行遍歷、上行遍歷、平行遍歷。

BeautifulSoup類型是標籤樹的根節點。

①標籤樹的下行遍歷:

屬性 說明
.contents 子節點的列表,將<tag>所有兒子節點存入列表
.children 子節點的迭代類型,與.contents類似,用於循環遍歷兒子節點
.descendants 子孫節點的迭代類型,包含所有子孫節點,用於循環遍歷
# 標籤樹的下行遍歷
soup = BeautifulSoup(demo, 'html.parser')
soup.head
print(soup.head)
soup.head.contents
print(soup.head.contents)
soup.body.contents
print(soup.body.contents)
len(soup.body.contents)
print(len(soup.body.contents))
len(soup.body.contents[1])
print(len(soup.body.contents[1]))

for child in soup.body.children:  # 遍歷兒子節點。
    print(child)
for child in soup.body.descendants:  # 遍歷子孫節點。
    print(child)

 ②標籤樹的上行遍歷:

屬性 說明
.parent 節點的父親標籤
.parents 節點先輩標籤的迭代類型,用於循環遍歷先輩節點
# 標籤樹的上行遍歷
soup = BeautifulSoup(demo, 'html.parser')
soup.title.parent
print(soup.title.parent)
soup.html.parent
print(soup.html.parent)
soup.parent
print(soup.parent)

soup = BeautifulSoup(demo, 'html.parser')
for parent in soup.a.parents:  # 遍歷soup的a標籤的先輩標籤。
    if parent is None:
        print(parent)
    else:
        print(parent.name)

遍歷所有先輩節點,包括soup本身,所以要區別判斷。

③標籤樹的平行遍歷:

屬性 說明
.next_sibling 返回按照HTML文本順序的下一個平行節點標籤
.previous_sibling 返回按照HTML文本順序的上一個平行節點標籤
.next_siblings 迭代類型,返回按照HTML文本順序的後續所有平行結點標籤
.previous_siblings 迭代類型,返回按照HTML文本順序的前續所有平行節點標籤

平行遍歷發生在同一個父節點下的各節點間。

# 標籤樹的平行遍歷
soup = BeautifulSoup(demo, 'html.parser')
soup.a.next_sibling
print(soup.a.next_sibling)
soup.a.next_sibling.next_sibling
print(soup.a.next_sibling.next_sibling)
soup.a.previous_sibling
print(soup.a.previous_sibling)
soup.a.previous_sibling.previous_sibling
print(soup.a.previous_sibling.previous_sibling)
soup.a.parent
print(soup.a.parent)

for sibling in soup.a.next_sibling:  # 遍歷後續節點。
    print(sibling)
for sibling in soup.a.previous_sibling:  # 遍歷前續節點。
    print(sibling)

4、基於bs4庫的HTML格式輸出

如何能讓HTML頁面更加友好的顯示?

(1)bs4庫的prettify()方法

# bs4庫的prettify()方法
import requests

r = requests.get("http://python123.io/ws/demo.html")
demo = r.text

from bs4 import BeautifulSoup

soup = BeautifulSoup(demo, 'html.parser')
soup.prettify()
print(soup.prettify())
print(soup.a.prettify())

.prettify()爲HTML文本<>及其內容增加更加’\n’,.prettify()可用於標籤,方法:<tag>.prettify()。

(2)bs4庫的編碼

# bs4庫的編碼
soup = BeautifulSoup("<p>中文</p>", "html.parser")
soup.p.string  # 默認使用UTF‐8編碼。
print(soup.p.string)
print(soup.p.prettify())

bs4庫將任何HTML輸入都變成UTF‐8編碼,Python 3.x默認支持編碼是UTF‐8,解析無障礙。

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