»
S
I
D
E
B
A
R
«
hyer开发笔记之:HTMLParser不支持中文问题
June 4th, 2009 by 一米六二

在开发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>
就能解析中文属性了。


3 Responses  
  • musf CHINA Windows XP Internet Explorer 7.0 writes:
    June 7th, 2009 at 4:58 pm

    帮我解决了中文问题谢谢!

  • 策划书 CHINA Windows Server 2003 Internet Explorer 6.0 writes:
    June 21st, 2009 at 2:55 pm

    向你多加学习

  • eic CHINA Fedora Linux Mozilla Firefox 3.5.1 writes:
    July 30th, 2009 at 2:36 am

    thanks, I will try this.


Leave a Reply

»  Substance: WordPress   »  Style: Ahren Ahimsa
16828 页面访问次数, 491 今天
7720 访问数, 161 今天
FireStats icon 由FireStats提供支持