Home  >  Article  >  Backend Development  >  Practical tips for crawling websites with python

Practical tips for crawling websites with python

高洛峰
高洛峰Original
2017-02-25 13:41:511260browse

Preface

The scripts I have written have one thing in common. They are all related to the web. Some methods of obtaining links are always used, and a lot of crawlers have accumulated. Let me summarize the experience of the website here, so that you don’t have to repeat the work when making things in the future.

1. The most basic website grabbing

import urllib2
content = urllib2.urlopen('http://XXXX').read()

2. Use a proxy server

This is more useful in certain situations, such as the IP is blocked, or the number of IP visits is limited, etc.

import urllib2
proxy_support = urllib2.ProxyHandler({'http':'http://XX.XX.XX.XX:XXXX'})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.urlopen('http://XXXX').read()

3. Situations that require login

The login situation is more troublesome for me. Let’s break down the problem:

3.1 Cookie processing

import urllib2, cookielib
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.urlopen('http://XXXX').read()

Yes, if you want to use a proxy at the same time and cookies, then add proxy_support and then change operner to

opener = urllib2.build_opener(proxy_support, cookie_support, urllib2.HTTPHandler)

##3.2 Form processing

A form is required to log in. How to fill in the form? First, use the tool to intercept the content of the form to be filled out.

For example, I usually use the firefox+httpfox plug-in to see what packages I have sent

Let me give you an example. Take verycd as an example. First find the POST you sent. Request, and POST form items:

Practical tips for crawling websites with python## If you can see verycd, you need to fill in

username, password, continueURI, fk, login_submit

, among which fk It is randomly generated (actually not too random, it looks like it is generated by simply encoding the epoch time). It needs to be obtained from the web page, which means that you must first visit the web page and use tools such as regular expressions to intercept the returned data. fk item. continueURI, as the name suggests, can be written casually, while login_submit is fixed , which can be seen from the source code. And username, password is obvious. Okay, with the data to be filled in, we have to generate postdata

import urllib
postdata=urllib.urlencode({
 'username':'XXXXX',
 'password':'XXXXX',
 'continueURI':'http://www.verycd.com/',
 'fk':fk,
 'login_submit':'登录'
})

Then generate an http request, and then send the request:

req = urllib2.Request(
 url = 'http://secure.verycd.com/signin/*///m.sbmmt.com/',
 data = postdata
)
result = urllib2.urlopen(req).read()

3.3 Disguise as a browser to visit

Some websites are disgusted with the visit of crawlers, so they reject all crawlers ask. At this time we need to disguise ourselves as a browser, which can be achieved by modifying the header in the http package:

headers = {
 'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
}
req = urllib2.Request(
 url = 'http://secure.verycd.com/signin/*///m.sbmmt.com/',
 data = postdata,
 headers = headers
)

3.4 Anti-"anti-hotlinking"

Some sites have so-called anti-leeching settings. In fact, it is very simple to put it bluntly. It is to check whether the referer site is its own in the header of the request you send, so we only need to do the same as in 3.3. Just change the referer of headers to the website. Take the famous shady cnbeta as an example:

headers = {
 'Referer':'http://www.cnbeta.com/articles'
}

headers is a dict data structure, you can put any The header you want to make some disguise. For example, some smart websites always like to peek into people's privacy. If someone accesses through a proxy, they will read the X-Forwarded-For in the header to see the person's real IP. If there is nothing to say, then just put the X-Forwarded-For Change it, you can change it to anything fun to bully and bully him, haha.

3.5 The ultimate trick

Sometimes even if you do 3.1-3.4, the access will still be blocked, so there is no other way, honestly remove the headers seen in httpfox If you write them all down, that's usually fine. If it doesn't work, then you can only use the ultimate trick. Selenium directly controls the browser for access. As long as the browser can do it, it can also do it. Similar ones include pamie, watir, etc.

4. Multi-threaded concurrent crawlingIf a single thread is too slow, multi-threading is needed. Here is a simple thread pool The template program simply prints 1-10, but it can be seen that it is done concurrently.

from threading import Thread
from Queue import Queue
from time import sleep
#q是任务队列
#NUM是并发线程总数
#JOBS是有多少任务
q = Queue()
NUM = 2
JOBS = 10
#具体的处理函数,负责处理单个任务
def do_somthing_using(arguments):
 print arguments
#这个是工作进程,负责不断从队列取数据并处理
def working():
 while True:
  arguments = q.get()
  do_somthing_using(arguments)
  sleep(1)
  q.task_done()
#fork NUM个线程等待队列
for i in range(NUM):
 t = Thread(target=working)
 t.setDaemon(True)
 t.start()
#把JOBS排入队列
for i in range(JOBS):
 q.put(i)
#等待所有JOBS完成
q.join()

5. Handling of verification codeWhat should I do if I encounter a verification code? There are two situations to deal with here:

1. Google’s kind of verification code, cold

2. Simple verification code: the number of characters is limited, and only simple translation or rotation plus noise is used Without distortion, it is still possible to deal with this kind of problem. The general idea is to rotate it back, remove the noise, and then divide the individual characters. After the division is completed, use the feature extraction method (such as PCA) to reduce the dimension and generate a feature library. , and then compare the verification code with the feature database. This is quite complicated and cannot be explained in one blog post, so I won’t go into details here. Please get a relevant textbook to study the specific methods.

In fact, some verification codes are still very weak, so I won’t name them here. Anyway, I have extracted verification codes with very high accuracy through the method 2, so 2 is actually feasible.

6 gzip/deflate support

现在的网页普遍支持gzip压缩,这往往可以解决大量传输时间,以 VeryCD 的主页为例,未压缩版本247K,压缩了以后45K,为原来的1/5。这就意味着抓取速度会快5倍。

然而python的urllib/urllib2默认都不支持压缩,要返回压缩格式,必须在request的header里面写明'accept-encoding',然后读取response后更要检查header查看是否有'content-encoding'一项来判断是否需要解码,很繁琐琐碎。如何让urllib2自动支持gzip, defalte呢?

其实可以继承 BaseHanlder 类,然后build_opener的方式来处理:

import urllib2
from gzip import GzipFile
from StringIO import StringIO
class ContentEncodingProcessor(urllib2.BaseHandler):
 """A handler to add gzip capabilities to urllib2 requests """
 
 # add headers to requests
 def http_request(self, req):
 req.add_header("Accept-Encoding", "gzip, deflate")
 return req
 
 # decode
 def http_response(self, req, resp):
 old_resp = resp
 # gzip
 if resp.headers.get("content-encoding") == "gzip":
  gz = GzipFile(
     fileobj=StringIO(resp.read()),
     mode="r"
     )
  resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
  resp.msg = old_resp.msg
 # deflate
 if resp.headers.get("content-encoding") == "deflate":
  gz = StringIO( deflate(resp.read()) )
  resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code) # 'class to add info() and
  resp.msg = old_resp.msg
 return resp
 
# deflate support
import zlib
def deflate(data): # zlib only provides the zlib compress format, not the deflate format;
 try:    # so on top of all there's this workaround:
 return zlib.decompress(data, -zlib.MAX_WBITS)
 except zlib.error:
 return zlib.decompress(data)

然后就简单了,

encoding_support = ContentEncodingProcessor
opener = urllib2.build_opener( encoding_support, urllib2.HTTPHandler )
 
#直接用opener打开网页,如果服务器支持gzip/defalte则自动解压缩
content = opener.open(url).read()

7. 更方便地多线程

总结一文的确提及了一个简单的多线程模板,但是那个东东真正应用到程序里面去只会让程序变得支离破碎,不堪入目。在怎么更方便地进行多线程方面我也动了一番脑筋。先想想怎么进行多线程调用最方便呢?

1、用twisted进行异步I/O抓取

事实上更高效的抓取并非一定要用多线程,也可以使用异步I/O法:直接用twisted的getPage方法,然后分别加上异步I/O结束时的callback和errback方法即可。例如可以这么干:

from twisted.web.client import getPage
from twisted.internet import reactor
 
links = [ 'http://www.verycd.com/topics/%d/'%i for i in range(5420,5430) ]
 
def parse_page(data,url):
 print len(data),url
 
def fetch_error(error,url):
 print error.getErrorMessage(),url
 
# 批量抓取链接
for url in links:
 getPage(url,timeout=5) \
  .addCallback(parse_page,url) \ #成功则调用parse_page方法
  .addErrback(fetch_error,url)  #失败则调用fetch_error方法
 
reactor.callLater(5, reactor.stop) #5秒钟后通知reactor结束程序
reactor.run()

twisted人如其名,写的代码实在是太扭曲了,非正常人所能接受,虽然这个简单的例子看上去还好;每次写twisted的程序整个人都扭曲了,累得不得了,文档等于没有,必须得看源码才知道怎么整,唉不提了。

如果要支持gzip/deflate,甚至做一些登陆的扩展,就得为twisted写个新的 HTTPClientFactory 类诸如此类,我这眉头真是大皱,遂放弃。有毅力者请自行尝试。

2、设计一个简单的多线程抓取类

还是觉得在urllib之类python“本土”的东东里面折腾起来更舒服。试想一下,如果有个Fetcher类,你可以这么调用

f = Fetcher(threads=10) #设定下载线程数为10
for url in urls:
 f.push(url) #把所有url推入下载队列
while f.taskleft(): #若还有未完成下载的线程
 content = f.pop() #从下载完成队列中取出结果
 do_with(content) # 处理content内容

这么个多线程调用简单明了,那么就这么设计吧,首先要有两个队列,用Queue搞定,多线程的基本架构也和“技巧总结”一文类似,push方法和pop方法都比较好处理,都是直接用Queue的方法,taskleft则是如果有“正在运行的任务”或者”队列中的任务”则为是,也好办,于是代码如下:

import urllib2
from threading import Thread,Lock
from Queue import Queue
import time
 
class Fetcher:
 def __init__(self,threads):
  self.opener = urllib2.build_opener(urllib2.HTTPHandler)
  self.lock = Lock() #线程锁
  self.q_req = Queue() #任务队列
  self.q_ans = Queue() #完成队列
  self.threads = threads
  for i in range(threads):
   t = Thread(target=self.threadget)
   t.setDaemon(True)
   t.start()
  self.running = 0
 
 def __del__(self): #解构时需等待两个队列完成
  time.sleep(0.5)
  self.q_req.join()
  self.q_ans.join()
 
 def taskleft(self):
  return self.q_req.qsize()+self.q_ans.qsize()+self.running
 
 def push(self,req):
  self.q_req.put(req)
 
 def pop(self):
  return self.q_ans.get()
 
 def threadget(self):
  while True:
   req = self.q_req.get()
   with self.lock: #要保证该操作的原子性,进入critical area
    self.running += 1
   try:
    ans = self.opener.open(req).read()
   except Exception, what:
    ans = ''
    print what
   self.q_ans.put((req,ans))
   with self.lock:
    self.running -= 1
   self.q_req.task_done()
   time.sleep(0.1) # don't spam
 
if __name__ == "__main__":
 links = [ 'http://www.verycd.com/topics/%d/'%i for i in range(5420,5430) ]
 f = Fetcher(threads=10)
 for url in links:
  f.push(url)
 while f.taskleft():
  url,content = f.pop()
  print url,len(content)

8. 一些琐碎的经验

1、连接池:

opener.open和urllib2.urlopen一样,都会新建一个http请求。通常情况下这不是什么问题,因为线性环境下,一秒钟可能也就新生成一个请求;然而在多线程环境下,每秒钟可以是几十上百个请求,这么干只要几分钟,正常的有理智的服务器一定会封禁你的。

然而在正常的html请求时,保持同时和服务器几十个连接又是很正常的一件事,所以完全可以手动维护一个 HttpConnection 的池,然后每次抓取时从连接池里面选连接进行连接即可。

这里有一个取巧的方法,就是利用squid做代理服务器来进行抓取,则squid会自动为你维护连接池,还附带数据缓存功能,而且squid本来就是我每个服务器上面必装的东东,何必再自找麻烦写连接池呢。

2、设定线程的栈大小

栈大小的设定将非常显著地影响python的内存占用,python多线程不设置这个值会导致程序占用大量内存,这对openvz的vps来说非常致命。stack_size必须大于32768,实际上应该总要32768*2以上

from threading import stack_size
stack_size(32768*16)

3、设置失败后自动重试

 def get(self,req,retries=3):
  try:
   response = self.opener.open(req)
   data = response.read()
  except Exception , what:
   print what,req
   if retries>0:
    return self.get(req,retries-1)
   else:
    print 'GET Failed',req
    return ''
  return data

4、设置超时

 import socket
 socket.setdefaulttimeout(10) #设置10秒后连接超时

登陆更加简化了,首先build_opener中要加入cookie支持,如要登陆 VeryCD ,给Fetcher新增一个空方法login,并在 init ()中调用,然后继承Fetcher类并override login方法:

def login(self,username,password):
 import urllib
 data=urllib.urlencode({'username':username,
       'password':password,
       'continue':'http://www.verycd.com/',
       'login_submit':u'登录'.encode('utf-8'),
       'save_cookie':1,})
 url = 'http://www.verycd.com/signin'
 self.opener.open(url,data).read()

于是在Fetcher初始化时便会自动登录 VeryCD 网站。

9. 总结

如此,以上就是总结Practical tips for crawling websites with python的全部内容了,本文内容代码简单,使用方便,性能也不俗,相信对各位使用python有很大的帮助。

更多Practical tips for crawling websites with python相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn