【问题标题】:HTMLParser - only extract img tagHTMLParser - 只提取 img 标签
【发布时间】:2013-11-25 10:56:42
【问题描述】:

我正在使用 HTMLParser 从简单的 html 文本中提取图像 url,如下所示:

html = <p><span style="font-size: 17px;"><span style="color: #993300;"><img style="margin-right: 15px; vertical-align: top;" src="images/announcements.png" alt="announcements" /><cite>some message I would like to preserve with its formatting</cite></span></span></p>

现在我还需要没有 img 标签的上述 html 版本,但在正确的位置关闭标签时遇到困难。这是我尝试过的:

class MyHtmlParser(HTMLParser):
    '''
    Parse simple url to extract data and image url.
    This is expecting a simple url containing only one data block and one iimage url.
    '''
    def __init__(self):
        HTMLParser.__init__(self)
        self.noImgHtml = ''

    def handle_starttag(self, tag, attrs):
        if tag == 'img':
            for a in attrs:
                if a[0] == 'src':
                    self.imageUrl = a[1]
        else:
            print '<%s>' % tag
            self.noImgHtml += '<%s>' % tag
            for a in attrs:
                print '%s=%s' % a
                self.noImgHtml += '%s=%s' % a

    def handle_endtag(self, tag):
        self.noImgHtml += '</%s>' % tag

    def handle_data(self, data):
        self.noImgHtml += data

MyHtmlParser().feed(html) 的输出是这样的:

<b>LATEST NEWS:</b><p><span>style=font-size: 17px;<span>style=color: #993300;</img><cite>The image uploader works again, so make sure to use some screenshots in your uploads/tutorials to make your submission look extra nice</cite></span></span></p>

如您所见(正如我的代码流所预期的那样),标签并没有像在原始 html 中那样关闭(例如 span>)。

这可以用 HTMLParser 轻松完成,还是我应该求助于 RE 来提取图像标签(这看起来不太优雅)?

我不能使用外部模块来执行此操作,因此需要使用 HTMLParser 提供的功能。

提前致谢, 坦率的

【问题讨论】:

    标签: python html


    【解决方案1】:

    其实你的代码是可以工作的,你可以使用

    parser = MyHtmlParser()
    parser.feed(html)
    parser.noImgHtml
    

    真的是你想要的。我试了一下,输出是

    <p><span>style=font-size: 17px;<span>style=color: #993300;</img><cite>some message I would like to preserve with its formatting</cite></span></span></p>
    

    除了需要把handle_endtag函数改成

    def handle_endtag(self, tag):
        if tag != 'img'
            self.noImgHtml += '</%s>' % tag
    

    排除img 的结束标签。

    实际上MyHtmlParser().feed(html) 只是print 结果,它什么也不返回。原因 标签在打印输出中没有正确关闭是你没有printendtag 以及handle_endtaghandle_data 中的标签内容。

    如果您正在尝试处理嵌套 div,Alex 在这里的回答可能会有所帮助。 How can I use the python HTMLParser library to extract data from a specific div tag? .

    【讨论】:

    • 谢谢,但这仍然不会使标签的属性格式正确,对吧?我只是偶然发现了 HTMLParser.get_starttag_text() 这似乎是我重建原始 html 所需要的
    • 我看到这里的问题,你也可以调整handle_starttag方法,在else部分,先添加&lt;tag,然后添加attrs,然后关闭&gt;。跨度>
    • 但显然应该使用get_starttag_text,因为我们不需要重新发明轮子。
    【解决方案2】:

    HTMLParser.get_starttag_text() 似乎是重建原始 html 的门票。这似乎有效:

    class MyHtmlParser(HTMLParser):
        '''
        Parse simple url to extract data and image url.
        This is expecting a simple url containing only one data block and one iimage url.
        '''
        def __init__(self):
            HTMLParser.__init__(self)
            self.noImgHtml = ''
    
        def handle_starttag(self, tag, attrs):
            if tag == 'img':
                for a in attrs:
                    if a[0] == 'src':
                        self.imageUrl = a[1]
            else:
                self.noImgHtml += self.get_starttag_text()
    
    
        def handle_endtag(self, tag):
            if tag != 'img':
                self.noImgHtml += '</%s>' % tag
    
        def handle_data(self, data):
            self.noImgHtml += data
            self.text = data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      相关资源
      最近更新 更多