HTMLParser或urllib2 unicode问题

时间:2013-12-20 18:08:36

标签: python unicode

我正在尝试使用HTMLParser和urllib2来获取图像文件

content = urllib2.urlopen( imgurl.encode('utf-8') ).read()
try:
    p = MyHTMLParser(  )
    p.feed( content )
    p.download_file( )
    p.close()
except Exception,e:
    print e

MyHTMLParser:

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)        
        self.url=""
        self.outfile = "some.png"

    def download_file(self):
        urllib.urlretrieve( self.url, self.outfile )

    def handle_starttag(self, tag, attrs):
        if tag == "a":
           # after some manipulation here, self.url will have a img url
           self.url = "http://somewhere.com/Fondue%C3%A0.png"

当我运行脚本时,我得到了

Traceback (most recent call last):
File "test.py", line 59, in <module>
p.feed( data )
File "/usr/lib/python2.7/HTMLParser.py", line 114, in feed
self.goahead(0)
File "/usr/lib/python2.7/HTMLParser.py", line 158, in goahead
k = self.parse_starttag(i)
File "/usr/lib/python2.7/HTMLParser.py", line 305, in parse_starttag
attrvalue = self.unescape(attrvalue)
File "/usr/lib/python2.7/HTMLParser.py", line 472, in unescape
return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)
File "/usr/lib/python2.7/re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 56: ordinal not in range(128)

使用我在找到的建议,我做了.encode('utf-8')方法,但它仍然给我错误。怎么解决这个问题?感谢

1 个答案:

答案 0 :(得分:1)

替换

content = urllib2.urlopen( url.encode('utf-8') ).read()

content = urllib2.urlopen(url).read().decode('utf-8')

将响应解码为unicode。