Beautiful Soup - 提取標題標籤



<title> 標籤用於為頁面提供在瀏覽器標題欄中顯示的文字標題。它不是網頁主要內容的一部分。標題標籤始終位於 <head> 標籤內。

我們可以使用 Beautiful Soup 提取標題標籤的內容。我們解析 HTML 樹並獲取標題標籤物件。

示例

html = '''
<html>
   <head>
      <Title>Python Libraries</title>
   </head>
   <body>
      <p Hello World</p>
   </body>
</html>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html5lib")

title = soup.title
print (title)

輸出

<title>Python Libraries</title>

在 HTML 中,我們可以將 title 屬性與所有標籤一起使用。title 屬性提供了有關元素的其他資訊。當滑鼠懸停在元素上時,該資訊充當工具提示文字。

我們可以使用以下程式碼片段提取每個標籤的 title 屬性的文字:

示例

html = '''
<html>
   <body>
      <p title='parsing HTML and XML'>Beautiful Soup</p>
      <p title='HTTP library'>requests</p>
      <p title='URL handling'>urllib</p>
   </body>
</html>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html5lib")
tags = soup.find_all()
for tag in tags:
   if tag.has_attr('title'):
      print (tag.attrs['title'])

輸出

parsing HTML and XML
HTTP library
URL handling
廣告