【问题标题】:Python HTMLParser cannot parse complex custom tag attributePython HTMLParser 无法解析复杂的自定义标签属性
【发布时间】:2015-01-04 13:25:20
【问题描述】:

我正在尝试使用 HTMLParser 来解析以下 HTML 标签:

<input type="hidden" name="movingEventItemId" value="<dt:value property="movingEventItemId" javaScriptSafe="1"/>"/>

当我获得单个属性时,我希望它返回以下内容:

类型 - 隐藏

名称-movingEventItemId

值 -

但值返回为 -

Python 代码:

 quote = '[\\\'\\"]'

 class HiddenInputParser(HTMLParser):
   def handle_starttag(self, tag, attrs):
    if tag == 'input':
        id = self.findAttr('id', attrs)
        name = self.findAttr('name', attrs)
        if not name and not id:
            print('no name or id     ' + self.get_starttag_text())
        elif id is not None and name is not None and id != name:
            print('id != name    ' + self.get_starttag_text())
        else:
            id = (id if id else name)
            output = '<input type="hidden" id="' + id + '" name="' + id + '" '
            for attr in attrs:
                key = attr[0]
                if attr[1] and key != 'id' and key != 'name' and key != 'type':
                    matcher = re.search( key + '\\s*=\\s*(' + quote + ')', self.get_starttag_text(), re.IGNORECASE)
                    quote2 = matcher.group(1)
                    value = quote2 + attr[1] + quote2
                    output += ' ' + key + '=' + value
            output += '/>'
            print ( output )
    else:
        print ( self.get_starttag_text() )

    def findAttr(self, id, attrs):
      for attr in attrs:
          if attr[0] == id:
              return attr[1]


def fixHiddenInputs():
   inputParser = HiddenInputParser()
   files = []
   for extension in extensions:
      for root, dirnames, filenames in os.walk(path):
         for filename in fnmatch.filter(filenames, extension):
            for line in fileinput.input(os.path.join(root, filename), inplace=1):
                line = line.rstrip()
                if ( re.search( '<input.*type=' + quote + 'hidden' + quote,  line ) ):
                    inputParser.feed(line)
                else:
                    print( line)

def convertHiddenInputs():
   pass

convertHiddenInputs()
fixHiddenInputs()

代码是将id添加到给定name属性值的输入标签。最终结果应如下所示:

<input type="hidden" id="displayOptions" name="displayOptions" value="<dt:value property="movingEventItemId" javaScriptSafe="1"/>"/>

这就是我得到的:

<input type="hidden" id="displayOptions" name="displayOptions"  value="<dt:value property=" javascriptsafe="1"/>

【问题讨论】:

    标签: python html html-parsing custom-tags


    【解决方案1】:

    要为标签添加id,无需解析整行并获取每个属性。解决您的问题的更好方法是将 id 添加到元素中,而不管其余属性如何。如果您需要 idname 相同,看起来您已经获得了 name 属性就好了。只需使用您获得的name 并在其之前或之后附加id="NAME_VALUE"

    干杯!

    【讨论】:

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