溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python?Beautiful?Soup模塊如何使用

發(fā)布時(shí)間:2023-02-24 11:24:19 來(lái)源:億速云 閱讀:134 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“Python Beautiful Soup模塊如何使用”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Python Beautiful Soup模塊如何使用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。

一、模塊簡(jiǎn)介

Beautiful Soup 是一個(gè)可以從HTML或XML文件中提取數(shù)據(jù)的Python庫(kù).它能夠通過(guò)你喜歡的轉(zhuǎn)換器實(shí)現(xiàn)慣用的文檔導(dǎo)航,查找,修改文檔的方式.Beautiful Soup會(huì)幫你節(jié)省數(shù)小時(shí)甚至數(shù)天的工作時(shí)間.

二、方法利用

1、引入模塊

# 引入
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" rel="external nofollow"  class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" rel="external nofollow"  class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow"  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, 'html.parser')

四種解析器

Python?Beautiful?Soup模塊如何使用

2、幾個(gè)簡(jiǎn)單的瀏覽結(jié)構(gòu)化數(shù)據(jù)的方法

#獲取Tag,通俗點(diǎn)就是HTML中的一個(gè)個(gè)標(biāo)簽

#獲取Tag,通俗點(diǎn)就是HTML中的一個(gè)個(gè)標(biāo)簽
soup.title                    # 獲取整個(gè)title標(biāo)簽字段:<title>The Dormouse's story</title>
soup.title.name               # 獲取title標(biāo)簽名稱  :title
soup.title.parent.name        # 獲取 title 的父級(jí)標(biāo)簽名稱:head
soup.p                        # 獲取第一個(gè)p標(biāo)簽字段:<p class="title"><b>The Dormouse's story</b></p>
soup.p['class']               # 獲取第一個(gè)p中class屬性值:title
soup.p.get('class')           # 等價(jià)于上面
soup.a                        # 獲取第一個(gè)a標(biāo)簽字段
soup.find_all('a')            # 獲取所有a標(biāo)簽字段
soup.find(id="link3")         # 獲取屬性id值為link3的字段
soup.a['class'] = "newClass"  # 可以對(duì)這些屬性和內(nèi)容等等進(jìn)行修改
del bs.a['class']             # 還可以對(duì)這個(gè)屬性進(jìn)行刪除
soup.find('a').get('id')      # 獲取class值為story的a標(biāo)簽中id屬性的值
soup.title.string             # 獲取title標(biāo)簽的值  :The Dormouse's story

三、具體利用

1、獲取擁有指定屬性的標(biāo)簽

方法一:獲取單個(gè)屬性
soup.find_all('div',id="even")            # 獲取所有id=even屬性的div標(biāo)簽
soup.find_all('div',attrs={'id':"even"})    # 效果同上
方法二:
soup.find_all('div',id="even",class_="square")            # 獲取所有id=even并且class=square屬性的div標(biāo)簽
soup.find_all('div',attrs={"id":"even","class":"square"})    # 效果同上

2、獲取標(biāo)簽的屬性值

方法一:通過(guò)下標(biāo)方式提取
for link in soup.find_all('a'):
    print(link['href'])        //等同于 print(link.get('href'))
方法二:利用attrs參數(shù)提取
for link in soup.find_all('a'):
    print(link.attrs['href'])

3、獲取標(biāo)簽中的內(nèi)容

divs = soup.find_all('div')        # 獲取所有的div標(biāo)簽
for div in divs:                   # 循環(huán)遍歷div中的每一個(gè)div
    a = div.find_all('a')[0]      # 查找div標(biāo)簽中的第一個(gè)a標(biāo)簽      
    print(a.string)              # 輸出a標(biāo)簽中的內(nèi)容
如果結(jié)果沒(méi)有正確顯示,可以轉(zhuǎn)換為list列表

4、stripped_strings

去除\n換行符等其他內(nèi)容 stripped_strings

divs = soup.find_all('div')
for div in divs:
    infos = list(div.stripped_strings)        # 去掉空格換行等
    bring(infos)

四、輸出

1、格式化輸出prettify()

prettify() 方法將Beautiful Soup的文檔樹格式化后以Unicode編碼輸出,每個(gè)XML/HTML標(biāo)簽都獨(dú)占一行

markup = '<a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
soup.prettify()
# '<html>\n <head>\n </head>\n <body>\n  <a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >\n...'
print(soup.prettify())
# <html>
#  <head>
#  </head>
#  <body>
#   <a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
#    I linked to
#    <i>
#     example.com
#    </i>
#   </a>
#  </body>
# </html>

2、get_text()

如果只想得到tag中包含的文本內(nèi)容,那么可以調(diào)用 get_text() 方法,這個(gè)方法獲取到tag中包含的所有文版內(nèi)容包括子孫tag中的內(nèi)容,并將結(jié)果作為Unicode字符串返回:

markup = '<a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >\nI linked to <i>example.com</i>\n</a>'
soup = BeautifulSoup(markup)
soup.get_text()
u'\nI linked to example.com\n'
soup.i.get_text()
u'example.com'

讀到這里,這篇“Python Beautiful Soup模塊如何使用”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI