我正在尝试使用 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"/>