【问题标题】:Stepping through entities in Python 3.3 html.parser在 Python 3.3 html.parser 中单步执行实体
【发布时间】:2013-05-02 02:40:54
【问题描述】:

我有以下解析器:

class Parser(HTMLParser):

  def __init__(self):
    HTMLParser.__init__(self)
    self.tableCount = 0

  def handle_starttag(self, tag, attrs):
     if tag == "table":
       for attr in attrs:
         if attr[0] == "class" and attr[1] == "space":
           ## need to do some processing here

代替 cmets,我需要做的是在此点之后步进所有 HTML 实体,直到 table 标记结束(此代码仅在 tag == table 时运行,如上所示。

我该怎么做?我看不到任何方法可以逐步浏览此标签下的所有标签。请注意,我不能使用任何外部库,例如 BeautifulSoup(只是 Python 标准库)。

【问题讨论】:

    标签: python html-parsing python-3.3


    【解决方案1】:
    class Parser(HTMLParser):
    
        def __init__(self):
            HTMLParser.__init__(self)
            self.inTable = False
    
        def handle_starttag(self, tag, attrs):
            if tag == "table" and ('class','space') in attrs:
                self.inTable = True
            if self.inTable:
                doSomething()
    
        def handle_endtag(self, tag):
            if tag == "table":
                self.inTable = False
    

    我猜xml.etree.ElementTree 可能更容易用于这种情况。

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 2016-10-22
      • 1970-01-01
      • 2014-09-02
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 2017-02-02
      相关资源
      最近更新 更多