Beautiful Soup - 物件型別



當我們將 HTML 文件或字串傳遞給 BeautifulSoup 建構函式時,BeautifulSoup 會將複雜的 HTML 頁面轉換為不同的 Python 物件。下面我們將討論 bs4 包中定義的四種主要物件型別。

  • 標籤 (Tag)
  • 可導航字串 (NavigableString)
  • BeautifulSoup
  • 註釋 (Comments)

標籤物件 (Tag Object)

HTML 標籤用於定義各種型別的文字內容。BeautifulSoup 中的標籤物件對應於實際頁面或文件中的 HTML 或 XML 標籤。

示例

from bs4 import BeautifulSoup

soup = BeautifulSoup('<b class="boldest">TutorialsPoint</b>', 'lxml')
tag = soup.html
print (type(tag))

輸出

<class 'bs4.element.Tag'>

標籤包含許多屬性和方法,標籤的兩個重要特性是其名稱和屬性。

名稱 (tag.name)

每個標籤都有一個名稱,可以透過“.name”字尾訪問。tag.name 將返回標籤的型別。

示例

from bs4 import BeautifulSoup

soup = BeautifulSoup('<b class="boldest">TutorialsPoint</b>', 'lxml')
tag = soup.html
print (tag.name)

輸出

html

但是,如果我們更改標籤名稱,則 BeautifulSoup 生成的 HTML 標記中也會反映出相同的更改。

示例

from bs4 import BeautifulSoup

soup = BeautifulSoup('<b class="boldest">TutorialsPoint</b>', 'lxml')
tag = soup.html
tag.name = "strong"
print (tag)

輸出

<strong><body><b class="boldest">TutorialsPoint</b></body></strong>

屬性 (tag.attrs)

一個標籤物件可以擁有任意數量的屬性。在上面的示例中,標籤 <b class="boldest"> 具有一個名為“class”的屬性,其值為“boldest”。任何不是標籤的內容基本上都是屬性,並且必須包含一個值。“attrs”返回屬性及其值的字典。您也可以透過訪問鍵來訪問屬性。

在下面的示例中,Beautifulsoup() 建構函式的字串引數包含 HTML 輸入標籤。“attr”返回輸入標籤的屬性。

示例

from bs4 import BeautifulSoup

soup = BeautifulSoup('<input type="text" name="name" value="Raju">', 'lxml')
tag = soup.input

print (tag.attrs)

輸出

{'type': 'text', 'name': 'name', 'value': 'Raju'}

我們可以使用字典運算子或方法對標籤的屬性進行各種修改(新增/刪除/修改)。

在下面的示例中,更新了 value 標籤。更新後的 HTML 字串顯示了更改。

示例

from bs4 import BeautifulSoup

soup = BeautifulSoup('<input type="text" name="name" value="Raju">', 'lxml')
tag = soup.input

print (tag.attrs)
tag['value']='Ravi'
print (soup)

輸出

<html><body><input name="name" type="text" value="Ravi"/></body></html>

我們添加了一個新的 id 標籤,並刪除了 value 標籤。

示例

from bs4 import BeautifulSoup

soup = BeautifulSoup('<input type="text" name="name" value="Raju">', 'lxml')
tag = soup.input

tag['id']='nm'
del tag['value']
print (soup)

輸出

<html><body><input id="nm" name="name" type="text"/></body></html>

多值屬性

一些 HTML5 屬性可以具有多個值。最常用的屬性是 class 屬性,它可以具有多個 CSS 值。其他屬性包括“rel”、“rev”、“headers”、“accesskey”和“accept-charset”。Beautiful Soup 中的多值屬性顯示為列表。

示例

from bs4 import BeautifulSoup

css_soup = BeautifulSoup('<p class="body"></p>', 'lxml')
print ("css_soup.p['class']:", css_soup.p['class'])

css_soup = BeautifulSoup('<p class="body bold"></p>', 'lxml')
print ("css_soup.p['class']:", css_soup.p['class'])

輸出

css_soup.p['class']: ['body']
css_soup.p['class']: ['body', 'bold']

但是,如果任何屬性包含多個值,但根據任何版本的 HTML 標準它都不是多值屬性,Beautiful Soup 將保留該屬性不變。

示例

from bs4 import BeautifulSoup

id_soup = BeautifulSoup('<p id="body bold"></p>', 'lxml')
print ("id_soup.p['id']:", id_soup.p['id'])
print ("type(id_soup.p['id']):", type(id_soup.p['id']))

輸出

id_soup.p['id']: body bold
type(id_soup.p['id']): <class 'str'>

可導航字串物件 (NavigableString object)

通常,某個字串位於某種型別的起始和結束標籤之間。瀏覽器的 HTML 引擎在渲染元素時會對字串應用預期的效果。例如,在 <b>Hello World</b> 中,你會發現一個字串位於 <b> 和 </b> 標籤之間,因此它以粗體顯示。

NavigableString 物件表示標籤的內容。它是 bs4.element.NavigableString 類的物件。要訪問內容,請使用 tag.string。

示例

from bs4 import BeautifulSoup
soup = BeautifulSoup("<h2 id='message'>Hello, Tutorialspoint!</h2>", 'html.parser')

print (soup.string)

print (type(soup.string))

輸出

Hello, Tutorialspoint!
<class 'bs4.element.NavigableString'>

NavigableString 物件類似於 Python Unicode 字串。它的某些特性支援遍歷樹和搜尋樹。可以使用 str() 函式將 NavigableString 轉換為 Unicode 字串。

示例

from bs4 import BeautifulSoup
soup = BeautifulSoup("<h2 id='message'>Hello, Tutorialspoint!</h2>",'html.parser')

tag = soup.h2
string = str(tag.string)
print (string)

輸出

Hello, Tutorialspoint!

與 Python 字串一樣,NavigableString 也是不可變的,不能就地修改。但是,可以使用 replace_with() 用另一個字串替換標籤的內部字串。

示例

from bs4 import BeautifulSoup
soup = BeautifulSoup("<h2 id='message'>Hello, Tutorialspoint!</h2>",'html.parser')

tag = soup.h2
tag.string.replace_with("OnLine Tutorials Library")
print (tag.string)

輸出

OnLine Tutorials Library

BeautifulSoup 物件

BeautifulSoup 物件表示整個已解析的物件。但是,它可以被認為類似於 Tag 物件。當我們嘗試抓取網路資源時建立的物件。因為它類似於 Tag 物件,所以它支援解析和搜尋文件樹所需的功能。

示例

from bs4 import BeautifulSoup
fp = open("index.html")
soup = BeautifulSoup(fp, 'html.parser')

print (soup)
print (soup.name)
print ('type:',type(soup))

輸出

<html>
<head>
<title>TutorialsPoint</title>
</head>
<body>
<h2>Departmentwise Employees</h2>
<ul>
<li>Accounts</li>
<ul>
<li>Anand</li>
<li>Mahesh</li>
</ul>
<li>HR</li>
<ul>
<li>Rani</li>
<li>Ankita</li>
</ul>
</ul>
</body>
</html>
[document]
type: <class 'bs4.BeautifulSoup'>

BeautifulSoup 物件的 name 屬性始終返回“[document]”。

如果將 BeautifulSoup 物件作為引數傳遞給某個函式(例如 replace_with()),則可以組合兩個已解析的文件。

示例

from bs4 import BeautifulSoup
obj1 = BeautifulSoup("<book><title>Python</title></book>", features="xml")
obj2 = BeautifulSoup("<b>Beautiful Soup parser</b>", "lxml")

obj2.find('b').replace_with(obj1)
print (obj2)

輸出

<html><body><book><title>Python</title></book></body></html>

註釋物件 (Comment object)

在 HTML 和 XML 文件中,寫在 <!-- 和 --> 之間的任何文字都被視為註釋。BeautifulSoup 可以將此類註釋文字檢測為 Comment 物件。

示例

from bs4 import BeautifulSoup
markup = "<b><!--This is a comment text in HTML--></b>"
soup = BeautifulSoup(markup, 'html.parser')
comment = soup.b.string
print (comment, type(comment))

輸出

This is a comment text in HTML <class 'bs4.element.Comment'>

Comment 物件是一種特殊的 NavigableString 物件。prettify() 方法以特殊格式顯示註釋文字:

示例

print (soup.b.prettify())

輸出

<b>
   <!--This is a comment text in HTML-->
</b>
廣告