Python中urlopen()处理gbk页面时的编码问题
我的代码在这里:
# coding:utf-8
if __name__ == '__main__':
from urllib2 import urlopen
url = 'http://iccna.blog.sohu.com/164572951.html'
data = urlopen(url).read()
soup = BeautifulSoup(data,fromEncoding='gb18030')
print WebExtractor(soup)
但是在调试的时候,数据是这样的:
��5h�,��4�H�5��VM��\
我该怎么做才能得到适合BeautifulSoup的数据呢?谢谢!
1 个回答
1
问题是服务器返回的数据是用Gzip压缩过的。你可以试试这个:
#-*- coding: utf-8 -*-
from __future__ import print_function
import gzip
import StringIO
import urllib2
from BeautifulSoup import BeautifulSoup
url = 'http://iccna.blog.sohu.com/164572951.html'
response = urllib2.urlopen(url)
data = response.read()
data = StringIO.StringIO(data)
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()
soup = BeautifulSoup(html, fromEncoding='gbk')
print(soup)
在我的系统上中文字符看起来还是不对,但这可能会给你一个正确的方向。