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
广告

© . All rights reserved.