在开发hyer的过程中,我发现beautifulsoup解析中文网页总是有问题。于是乎,我决定用tidy来在beautifulsoup之前做一个fix.没想到tidy的python极其不雅,首先tidy的强大在python版的uTidylib也完全感觉不到了,而且安装的时候时候还有错误。
等tidy问题终于修正之后,发现大量的网页已经能用美味的汤[beautifulsoup]来解决了,但是仍然有一部分网页 不行。
最终经过跟踪发现是在这里:(/usr/lib/python2.6/HTMLParser.py):
<coolcode>
attrfind = re.compile(
r’\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*’
r’(\’[^\']*\’|”[^"]*”|[-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~@]*))?’)
</coolcode>
正则表达式的第二行在遇到形如
<coolcode>
alt=我是中国人 height=60 src=’images/go.gif’>
</coolcode>
这样内容为中文不加引号的属性时无法处理。于是稍做修改(我是个大老粗,改得很偷懒,但是好像很管用)
<coolcode>
attrfind = re.compile(
r’\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*’
r’(\’[^\']*\’|”[^"]*”|[^\s^\'^\"]*))?’)
</coolcode>
就能解析中文属性了。