Python_Python2利用urllib2抓取中文网页乱码的问题

今天想用urllib2抓去网页源码,出现了问题,print打印显示乱码。

代码一:

response=urllib2.urlopen('http://caipiao.163.com/award/').read()

打印之后出现乱码问题。

【1】分析:首先怀疑是编码问题,于是看了网页源代码,发现是utf-8编码,编码是正确的。

<!DOCTYPE HTML>
<html>
<head>
<link rel="shortcut icon" href="/favicon.ico"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="application-name" content="caipiao.163.com"/>

注:网页编码的方式可见网页源代码首部,如上图。

【2】分析:编码正确,进过查阅资料。发现导致乱码问题有两个原因:1、编码问题  2、压缩格式的问题。很多网站也会以压缩格式的形式输出到页面,此时你去打印这个压缩包一样的东西,就会出错。                   

 解法:内置函数解压

response=urllib2.urlopen('http://caipiao.163.com/award/').read()
data = StringIO.StringIO(response)
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()
html=html.encode('utf8')
name1=re.findall(r'</em><strong>(.+)</strong>',html)
print name1[0]

【3】附一些爬虫技巧:http://www.open-open.com/lib/view/open1375945149312.html

【4】解压相关函数并没有去深入了解,用到在复习

猜你喜欢

转载自blog.csdn.net/m0_38034312/article/details/81080243
今日推荐