【问题标题】:Extracting Text / Parse Text with html.parser (Python)使用 html.parser (Python) 提取文本/解析文本
【发布时间】:2020-11-05 11:04:30
【问题描述】:

我想从 html 文件中提取文本,特别是从 <p><h1> 标记中。 我确实从 python 文档中看到了有关此主题的代码: 从 html.parser 导入 HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)

    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)

    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1></body></html>')

但我不确定如何从这里开始,以便仅提取某些标签内的文本(

和 .欢迎任何正确方向的提示和建议! (我不想使用漂亮的汤或任何外部库)

【问题讨论】:

    标签: python web-crawler html-parsing


    【解决方案1】:

    你可以使用这个例子来解析来自&lt;h1&gt;&lt;p&gt;标签的文本:

    from html.parser import HTMLParser
    
    class MyHTMLParser(HTMLParser):
    
        def __init__(self):
            super().__init__()
            self.data = []
            self.capture = False
    
        def handle_starttag(self, tag, attrs):
            if tag in ('p', 'h1'):
                self.capture = True
    
        def handle_endtag(self, tag):
            if tag in ('p', 'h1'):
                self.capture = False
    
        def handle_data(self, data):
            if self.capture:
                self.data.append(data)
    
    parser = MyHTMLParser()
    parser.feed('<html><head><title>Test</title></head>'
                '<body><h1>Parse me!</h1><p>This is P tag</p></body></html>')
    
    print(parser.data)
    

    打印:

    ['Parse me!', 'This is P tag']
    

    【讨论】:

      猜你喜欢
      • 2011-04-04
      • 2010-12-23
      • 2011-02-06
      • 2012-08-09
      • 2023-03-04
      • 2022-01-17
      • 1970-01-01
      • 2011-02-13
      • 2015-09-01
      相关资源
      最近更新 更多