BLOG
Enjoy when you can, and endure when you must.
DEC 13, 2013/Python
解析经过压缩后的网页

在《抓站进行曲》中,我们利用urllib2提供的方法成功得到了网页数据。不过对于数据的处理来说,还有一种情况没有考虑,如果网页内容是被压缩过呢?我们来抓取新浪新闻试试:

>>> req = urllib2.urlopen('http://news.sina.com.cn/c/2013-12-13/075828974213.shtml')
>>> data = req.read()
>>> data[1000:1300]
'\xa1j\x19\x10R\xa4\x8cA%=\tQ\xa6r\x8a!I\xa6\xbfC\xd2\x98DS\xe1;G\xfe\xb9\xb3\xb5R\x1aQw{\xa6XR>\xeb.Ic\xf9\x9c\xa4*\x15_\xad*W\xb6b_\xf8\xf2\xa5\x8c<\xb1;\xebv\xed\xdc74\xe8\xf2p\xa2(r]\x82g\xaa"\xab\xb5J\xa9\x1eg\xa5\xc7\xa4\n\x07\xd2A\xe5DnXk`^ \xed\xcb\x17s\xd8\xbcQ\xa5(\xfb\xf1=[\x90\xaa\xa3\xbeCU\xde\xabg\x84zH?Z\xe8\x91/\x17\x14\xe5p\xad\xac?\x90\xcee\x1ca)\xee\xabV\x15K\xd1CU?$\x15\x94\\\xbe\xe4[7\xa7RSI\xcedA\x9a\x94+\x96\xfc\xea!\xe8\xa2C\xb4\x9b\xe0\x07\xf2\x83t-\xf9\xa5r\x1e\x0b\x8e\xa7,\x993A\x0b\xe4\x8c@\xc4o\xd5\x9f\xaa\xa9*\xf2\x88\xa2\x12\xd2Z\x8a\x08\x96"\x85<d\xcc\xf9\x8f\x8e\xc2o\rZP\x06\x96\xb0\xe4o\x98\x18\x00\x8b|\xb6\x02l\xe1\xcf\x95\x92\x8c\x1f\x92jj\xddB=\xdd8\xa3\x08\x81n!\x0c\x0f\x11\xd2/\x85\xbc\xb5\x1c\xf6\xbe\xad\x18\x94\t\x06z\xa1\xcc\xb8\x9cO)i\xa9\x92i\xb3\xa6P\xa0G\x88\xfa\x19\x82\xfeP'

这看着确实有点畸形。要想得到正确的内容,那就必须解压!那首先需要检测压缩的类型,这很简单:

>>> res.headers.get('content-encoding')
'gzip'

从header中的content-encoding可以查看到该网页的压缩方式,接下来就是对症下药了,Python标准库里的gzip可以完成这里的需求。

>>> from gzip import GzipFile
>>> from StringIO import StringIO
>>> d = gz.read()
>>> d[1000:1300]
'ntent="http://news.sina.com.cn/c/2013-12-13/075828974213.shtml" />\n<meta property="og:image" content="" />\n<meta name="stencil" content="PGLS000115" />\n<meta name="publishid"  content="1,1,28974213">\n<meta name="comment" content="gn:1-1-28974213">\n\n<meta name="sudameta" content="comment_channel:gn; '

接下来,那就不用说了。

RECOMMENDS
COMMENTS
LEAVE COMMNT