Beautiful Soup - 查找所有注释



在计算机代码中插入注释被认为是一种良好的编程实践。注释有助于理解程序的逻辑,也作为文档。你可以在HTML和XML脚本中添加注释,就像在用C、Java、Python等语言编写的程序中一样。BeautifulSoup API可以帮助识别HTML文档中的所有注释。

在HTML和XML中,注释文本写在<!-- 和 --> 标签之间。

<!-- Comment Text -->

BeautifulSoup包(内部名称为bs4)将Comment定义为一个重要的对象。Comment对象是一种特殊的NavigableString对象。因此,在<!-- 和 -->之间找到的任何Tag的string属性都被识别为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'>

要搜索HTML文档中所有注释的出现,我们将使用find_all()方法。没有任何参数,find_all()返回解析的HTML文档中的所有元素。你可以将关键字参数'string'传递给find_all()方法。我们将把iscomment()函数的返回值赋给它。

comments = soup.find_all(string=iscomment)

iscomment()函数使用isinstance()函数验证标签中的文本是否是注释对象。

def iscomment(elem):
   return isinstance(elem, Comment)

comments变量将存储给定HTML文档中的所有注释文本。我们在示例代码中将使用以下index.html文件:

<html>
   <head>
      <!-- Title of document -->
      <title>TutorialsPoint</title>
   </head>
   <body>
      <!-- Page heading -->
      <h2>Departmentwise Employees</h2>
      <!-- top level list-->
      <ul id="dept">
      <li>Accounts</li>
         <ul id='acc'>
         <!-- first inner list -->
         <li>Anand</li>
         <li>Mahesh</li>
         </ul>
      <li>HR</li>
         <ul id="HR">
         <!-- second inner list -->
         <li>Rani</li>
         <li>Ankita</li>
         </ul>
      </ul>
   </body>
</html>

以下Python程序抓取上述HTML文档,并查找其中的所有注释。

示例

from bs4 import BeautifulSoup, Comment

fp = open('index.html')

soup = BeautifulSoup(fp, 'html.parser')

def iscomment(elem):
    return isinstance(elem, Comment)

comments = soup.find_all(string=iscomment)
print (comments)

输出

[' Title of document ', ' Page heading ', ' top level list', ' first inner list ', ' second inner list ']

上述输出显示所有注释的列表。我们也可以使用for循环遍历注释集合。

示例

i=0
for comment in comments:
   i+=1
   print (i,".",comment)

输出

1 .  Title of document 
2 .  Page heading
3 .  top level list
4 .  first inner list
5 .  second inner list

在本章中,我们学习了如何提取HTML文档中的所有注释字符串。

广告
© . All rights reserved.