4

我想在标签下获取整个 html 并使用 HTMLParser。我目前能够获取标签之间的数据,以下是我的代码

class LinksParser(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    self.recording = 0
    self.data = ''

  def handle_starttag(self, tag, attributes):
    if tag != 'span':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'itemprop' and value == 'description':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'span' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data += data

例如,我还想要输入中的 html 标签

<span itemprop="description">
<h1>My First Heading</h1>
<p>My first <br/><br/>paragraph.</p>
</span>

当作为输入提供时,只会给我没有标签的数据。有什么方法可以让我在标签之间获取整个 html 吗?

4

2 回答 2

5

可以使用xml.etree.ElementTree.TreeBuilderetree API 来查找/操作<span>元素:

import sys
from HTMLParser import HTMLParser
from xml.etree import cElementTree as etree

class LinksParser(HTMLParser):
  def __init__(self):
      HTMLParser.__init__(self)
      self.tb = etree.TreeBuilder()

  def handle_starttag(self, tag, attributes):
      self.tb.start(tag, dict(attributes))

  def handle_endtag(self, tag):
      self.tb.end(tag)

  def handle_data(self, data):
      self.tb.data(data)

  def close(self):
      HTMLParser.close(self)
      return self.tb.close()

parser = LinksParser()
parser.feed(sys.stdin.read())
root = parser.close()
span = root.find(".//span[@itemprop='description']")
etree.ElementTree(span).write(sys.stdout)

输出

<span itemprop="description">
<h1>My First Heading</h1>
<p>My first <br /><br />paragraph.</p>
</span>

要在没有父(根)<span>标签的情况下打印:

sys.stdout.write(span.text)
for child in span:
    sys.stdout.write(etree.tostring(child)) # add encoding="unicode" on Python 3
于 2012-11-11T19:22:20.247 回答
3

这是根据您提供的测试数据完成工作的方法,只需对现有代码进行最少的更改(假设它基本上已经在执行您想要的操作)。您可能希望将其扩展为以更强大的方式处理自闭合标签:

from HTMLParser import HTMLParser

class LinksParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.recording = 0
        self.data = ''
        self.self_closing_tags = ("br",)

    def handle_starttag(self, tag, attributes):
        if tag not in ('span',) + self.self_closing_tags:
            self.data += "<%s" % (tag,)
            if attributes:
                self.data += " " + " ".join('%s="%s"' % (k, v) for k, v in attributes)
            self.data += ">"
            return
        if self.recording:
            self.recording += 1
            return
        for name, value in attributes:
            if name == 'itemprop' and value == 'description':
                break
        else:
            return
        self.recording = 1 

    def handle_endtag(self, tag):
        if tag == 'span' and self.recording:
             self.recording -= 1
        elif tag in self.self_closing_tags:
             self.data += "<%s/"> % (tag,)
        else:
             self.data += "</%s>" % (tag,)

    def handle_data(self, data):
        if self.recording:
            self.data += data

鉴于此作为输入:

<span itemprop="description">
<h1>My First Heading</h1>
<p>My first <br/><br/>paragraph.</p>
</span>

输出是:

<h1>My First Heading</h1>
<p>My first <br/><br/>paragraph.</p>
于 2012-11-11T18:44:17.340 回答