Encoding problem downloading HTML using mechanize and Python 2.6

时间秒杀一切 提交于 2019-12-01 04:26:06

问题


browser = mechanize.Browser()
page = browser.open(url)
html = page.get_data()

print html

It shows some strange characters. I suppose that it is UTF-8 string but Python doesn't know that and cannot show it properly.

How can I convert this string to unicode string like

u = u'test'

回答1:


It was gzipped

def ungzipResponse(r,b):
    headers = r.info()
    if headers['Content-Encoding']=='gzip':
        import gzip
        gz = gzip.GzipFile(fileobj=r, mode='rb')
        html = gz.read()
        gz.close()
        headers["Content-type"] = "text/html; charset=utf-8"
        r.set_data( html )
        b.set_response(r)

response = browser.open(url)
ungzipResponse(response, browser)
html = response.read()



回答2:


u = html.decode('utf-8')



回答3:


you need to define the encoding like :

#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

mechanize need it .

for more information check this out http://www.python.org/dev/peps/pep-0263/



来源:https://stackoverflow.com/questions/3804572/encoding-problem-downloading-html-using-mechanize-and-python-2-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!