十五年测试老手,长期负责WEB\APP 项目测试,目前主要负责团队管理工作。

【转】使用python爬虫抓站的一些技巧总结:进阶篇

上一篇 / 下一篇  2011-04-06 23:43:03 / 个人分类:python

以前写过一篇使用python爬虫抓站的一些技巧总结,总结了诸多爬虫使用的方法;那篇东东现在看来还是挺有用的,但是当时很菜(现在也菜,但是比那时进步了不少),很多东西都不是很优,属于”只是能用”这么个层次。这篇进阶篇打算把“能用”提升到“用得省事省心”这个层次。51Testing软件测试网Yn'S4}Xgx
一、gzip/deflate支持
%Y nqu'r0
6kV5`f [zVs6RE0现在的网页普遍支持gzip压缩,这往往可以解决大量传输时间,以VeryCD的主页为例,未压缩版本247K,压缩了以后45K,为原来的1/5。这就意味着抓取速度会快5倍。
nj-^9N/?j051Testing软件测试网j9r0gB"L3u
然而python的urllib/urllib2默认都不支持压缩,要返回压缩格式,必须在request的header里面写明’accept- encoding’,然后读取response后更要检查header查看是否有’content-encoding’一项来判断是否需要解码,很繁琐琐碎。如何让urllib2自动支持gzip, defalte呢?
k4B5o&]:|Nv|051Testing软件测试网ev })e |MI1bv
其实可以继承BaseHanlder类,然后build_opener的方式来处理:
?p'z {'tMzj051Testing软件测试网7oq%@N$d+r5v t:\A
import urllib2
p"N#m}+Y2`/E qQ&z`0from gzip import GzipFile51Testing软件测试网'tL"f#I{o
from StringIO import StringIO
*I*taA)?0class ContentEncodingProcessor(urllib2.BaseHandler):
I&N]zN)K)B0  """A handler to add gzip capabilities to urllib2 requests """51Testing软件测试网/L%} iy!}o\Vx
 
P u;h,c`UrP P1p|0  # add headers to requests51Testing软件测试网h,QHMl dMgW
  def http_request(self, req):
y*m)` nB#S5H0    req.add_header("Accept-Encoding", "gzip, deflate")51Testing软件测试网2W8\a$|8h u wBVr@
    return req
_3D|0Hf0 
}~[zVG0  # decode
fAm-b p}5m0  def http_response(self, req, resp):51Testing软件测试网&Bf+BQ"RcBi5^j\
    old_resp = resp51Testing软件测试网 \qE#L;r
    # gzip51Testing软件测试网;n KsF*Q+M"w+r
    if resp.headers.get("content-encoding") == "gzip":
2Sm+l(Ew3x&YH?'JD3S0        gz = GzipFile(
j+Ld:sgT0                    fileobj=StringIO(resp.read()),
z U x1q6k/o.s{0                    mode="r"
G1@I$L(ng0                  )
*|P7b{0BCt5d0        resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)51Testing软件测试网 c"V,a M[;Zu,?
        resp.msg = old_resp.msg
`4aq/c3H'oaf0    # deflate
u-d4J)FT'T0    if resp.headers.get("content-encoding") == "deflate":51Testing软件测试网7`u4_0m N~#] }T
        gz = StringIO( deflate(resp.read()) )51Testing软件测试网-x U$D,i ~'oF&Z.S
        resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)  # 'class to add info() and
/ja6A)BiC0        resp.msg = old_resp.msg51Testing软件测试网&R^jH [
    return resp
BIw;i3|w0 51Testing软件测试网e2~ ]/EV/j(a
# deflate support51Testing软件测试网0q!N KwW!QB'd8US
import zlib
O/G4TC|u-Hm0def deflate(data):   # zlib only provides the zlib compress format, not the deflate format;51Testing软件测试网A+Cm{f y)T:U
  try:               # so on top of all there's this workaround:51Testing软件测试网wp5c,`jmzb5m q_
    return zlib.decompress51Testing软件测试网+xE5t-O,V2rA
51Testing软件测试网RlEjNW(d
           
B;K+tDw"br)g0

TAG: Python python

 

评分:0

我来说两句

Open Toolbar