views:

64

answers:

3
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  A: 
u = html.decode('utf-8')
Ned Batchelder
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: unexpected code byte
how
Then it isn't utf-8. You should examine the headers to see what character set is being returned.
Ned Batchelder
facebook.com, Content-Type: text/html; charset=utf-8
how
@how: Save the output to a file and open it in a UTF-aware editor or use a hex editor to see whether it's really UTF-8 what mechanize returns.
AndiDog
Sorry, it was gzipped. Forgot to ungzip :)
how
A: 

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()
how
Depending on what you're trying to do, you should really use an existing library that handles low-level stuff like this for you.
AndiDog
I've tried to find how to make it easier but it seems like the simplest solution.
how
A: 

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/

Gunslinger_
It was already there: # -*- coding: utf-8 -*-
how
but you need : # -*- coding: iso-8859-15 -*-not # -*- coding: utf-8 -*- –
Gunslinger_