---
title: "htmlparser 解析html标签中文属性且未加标签 bug解决办法"
author: "john2007"
date: "2009-12-30T16:25:43Z"
tags: []
categories: ["编程语言"]
slug: "htmlparser-html-bug"
draft: false
lastmod: "2009-12-30T16:26:36Z"
id: 559840
url: "https://john2007.iteye.com/blog/559840"
---

bug:

利用HTMLParser解析 带有中文属性的标签，例如："&lt;img alt=周润发 src="/html"/&gt;"

会出现如下错误：

 

raise HTMLParseError(message, self.getpos())

HTMLParser.HTMLParseError: junk characters in start tag: u'\\u5468\\u6da6\\u53d1 src="/html"/&gt;', at line 1, column 1

 

错误原因还是正则表达式惹的祸。

attrfind = re.compile(

    r'\\s\*(\[a-zA-Z\_]\[-.:a-zA-Z\_0-9]\*)(\\s\*=\\s\*'

    r'(\\'\[^\\']\*\\'|"\[^"]\*"|\[-a-zA-Z0-9./,:;+\*%?!&$\\(\\)\_#=~@]\*))?') 

attrfind 没有匹配中文字符。

 

解决办法：

修改attrfind:

attrfind = re.compile(

    ur'\\s\*(\[a-zA-Z\_]\[-.:a-zA-Z\_0-9]\*)(\\s\*=\\s\*'

    ur'(\\'\[^\\']\*\\'|"\[^"]\*"|\[-a-zA-Z0-9./,:;+\*%?!&$\\(\\)\_#=~@\\u4e00-\\u9fa5]\*))?')

 

然后案例测试如下：

 

htmldata="""&lt;img alt=周润发 src="/html"/&gt;""".decode("utf8")

 

没有错误。