【问题标题】:HTMLParser or urllib2 unicode issueHTMLParser 或 urllib2 unicode 问题
【发布时间】: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 是在我在运行时进行一些字符串操作之后出现的。所以我一开始就不知道确切的网址。
  • @dorothy:但问题仍然存在:url 是指向 HTML 页面(如 this),还是 PNG 图像的 URL(如 this)?跨度>

标签: python unicode


【解决方案1】:

替换

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

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

将响应解码为 un​​icode。

【讨论】:

  • @dorothy: utf-8 不是唯一可以在 html 文档中使用的字符编码。它可以在 http 标头(例如,Content-type: text/html; charset=utf-8)、html 内部(例如,&lt;meta charset="utf-8"&gt;)、etc 中指定
猜你喜欢
  • 2011-05-16
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 2012-05-20
  • 2012-07-27
  • 1970-01-01
  • 2011-10-17
相关资源
最近更新 更多