2008-04-27 16:54:37 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# vi:si:et:sw=2:sts=2:ts=2
|
2008-04-28 09:55:30 +00:00
|
|
|
import gzip
|
|
|
|
import StringIO
|
2008-04-27 16:54:37 +00:00
|
|
|
import urllib
|
|
|
|
import urllib2
|
|
|
|
|
|
|
|
import chardet
|
|
|
|
|
|
|
|
|
|
|
|
# Default headers for HTTP requests.
|
|
|
|
DEFAULT_HEADERS = {'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008041514 Firefox/3.0b5'}
|
|
|
|
|
|
|
|
def openUrl(url, data=None, headers=DEFAULT_HEADERS):
|
|
|
|
url = url.replace(' ', '%20')
|
|
|
|
req = urllib2.Request(url, data, headers)
|
2008-04-28 11:41:55 +00:00
|
|
|
req.add_header('Accept-Encoding', 'gzip')
|
2008-04-27 16:54:37 +00:00
|
|
|
return urllib2.urlopen(req)
|
|
|
|
|
|
|
|
def getUrl(url, data=None, headers=DEFAULT_HEADERS):
|
|
|
|
f = openUrl(url, data, headers)
|
|
|
|
data = f.read()
|
|
|
|
f.close()
|
2008-04-28 09:55:30 +00:00
|
|
|
if f.headers.get('content-encoding', None) == 'gzip':
|
|
|
|
data = gzip.GzipFile(fileobj=StringIO.StringIO(data)).read()
|
2008-04-27 16:54:37 +00:00
|
|
|
return data
|
|
|
|
|
|
|
|
def getUrlUnicode(url):
|
|
|
|
data = getUrl(url)
|
|
|
|
encoding = chardet.detect(data)['encoding']
|
|
|
|
if not encoding:
|
|
|
|
encoding = 'latin-1'
|
|
|
|
return unicode(data, encoding)
|
|
|
|
|