【问题标题】:Is there a way in beautiful soup to count the number of tags in a html page有没有办法在美丽的汤中计算html页面中的标签数量
【发布时间】:2012-12-13 04:35:50
【问题描述】:

我正在考虑在 python 中创建一个字典,其中键是 html 标签名称,值是标签出现的次数。有没有办法用漂亮的汤或其他东西来做到这一点?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    BeautifulSoup 非常适合 HTML 解析,您当然可以将它用于此目的。这将非常简单:

    from bs4 import BeautifulSoup as BS
    
    def num_apperances_of_tag(tag_name, html):
        soup = BS(html)
        return len(soup.find_all(tag_name))
    

    【讨论】:

      【解决方案2】:

      使用 BeautifulSoup,您可以通过省略搜索条件来搜索所有标签:

      # print all tags
      for tag in soup.findAll():
          print tag.name # TODO: add/update dict
      

      如果您只对出现次数感兴趣,BeautifulSoup 可能有点矫枉过正,在这种情况下您可以改用 HTMLParser

      from HTMLParser import HTMLParser
      
      class print_tags(HTMLParser):
          def handle_starttag(self, tag, attrs):
              print tag # TODO: add/update dict
      
      parser = print_tags()
      parser.feed(html)
      

      这将产生相同的输出。

      要创建{ 'tag' : count } 的字典,您可以使用collections.defaultdict

      from collections import defaultdict
      
      occurrences = defaultdict(int)
      # ...
      occurrences[tag_name] += 1
      

      【讨论】:

        【解决方案3】:

        这是我非常简单的解决方案:

        from html.parser import HTMLParser
        import requests
        
        
        class MyHTMLParser(HTMLParser):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.start_tags = []
                self.end_tags = []
        
            def handle_starttag(self, tag, attrs):
                self.start_tags.append(tag)
        
            def handle_endtag(self, tag):
                self.end_tags.append(tag)
        
        
        if __name__ == '__main__':
            parser = MyHTMLParser()
        
            html_response = requests.get('https://jetlend.ru/')
            parser.feed(html_response.text)
        
            print('Start tags:', len(parser.start_tags))
            print('End tags:', len(parser.start_tags))
            print('Amount:', len(parser.start_tags) + len(parser.start_tags))
        

        来源:https://docs.python.org/3/library/html.parser.html

        【讨论】:

          猜你喜欢
          • 2018-07-18
          • 1970-01-01
          • 1970-01-01
          • 2020-08-17
          • 2019-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多