【发布时间】:2013-12-20 18:08:35
【问题描述】:
我正在尝试使用 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)
使用我在 find 中找到的建议,我执行了 .encode('utf-8') 方法,但它仍然给我错误。如何解决这个问题?谢谢
【问题讨论】:
-
该错误消息应该带有一个文件名和行号,指出哪一行给出了错误。是哪条线?
-
@SamMussmann,我添加了实际的追溯。谢谢
-
HTML 解析器解析 HTML。那是真实的图像。为什么不直接下载文件?
-
@Blender,实际上 img url 是在我在运行时进行一些字符串操作之后出现的。所以我一开始就不知道确切的网址。