1

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

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

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

类型 - 隐藏

名称 -movingEventItemId

值 - < dt:value property="movingEventItemId" javaScriptSafe="1" />

但价值回来了 - < dt:value property=" javascriptsafe="1"/>

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"/>
4

1 回答 1

0

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

干杯!

于 2014-11-07T20:04:40.227 回答