1. 程式人生 > >Beautifulsoup模塊

Beautifulsoup模塊

software group 父節點 text 選擇 rom prettify 更多 基本

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、兄弟節點
技術分享圖片
#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" 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)
print(soup.head)
print(type(soup.head)) #<class ‘bs4.element.Tag‘>

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

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

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

#4、獲取表的內容
print(soup.p.string)

‘‘‘
對下面的這種結構,soup.p.string 返回為None,因為裏面有a
<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、子節點、子孫節點
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>;
    and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,lxml)

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(soup.a.next_siblings) #得到生成器對象
print(soup.a.previous_siblings) #得到生成器對象
View Code

四 標準選擇器

技術分享圖片
#find與findall:用法完全一樣,可根據標簽名,屬性,內容查找文檔,但是find只找第一個元素
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>;
    and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,lxml)

#1、按照標簽名查找
# print(soup.find_all(‘a‘))
# print(soup.find_all(‘a‘,id=‘link3‘))
# print(soup.find_all(‘a‘,id=‘link3‘,attrs={‘class‘:"sister"}))
#
# print(soup.find_all(‘a‘)[0].find(‘span‘)) #嵌套查找


#2、按照屬性查找
# print(soup.p.find_all(attrs={‘id‘:‘link1‘})) #等同於print(soup.find_all(id=‘link1‘))
# print(soup.p.find_all(attrs={‘class‘:‘sister‘}))
#
# print(soup.find_all(class_=‘sister‘))


#3、按照文本內容查找
print(soup.p.find_all(text="The Dormouse‘s story")) # 按照完整內容匹配(是==而不是in),得到的結果也是內容

#更多:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find
find與findall

五 CSS選擇器

技術分享圖片
##該模塊提供了select方法來支持css
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

六 總結

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

Beautifulsoup模塊