Python爬虫的一些总结

最近写了一些爬虫,总结下遇到过的一些问题.


###常用库:

  • 抓取网页: 常用的有requests, urllib.
  • 解析: BeautifulSoup, lxml, re.
  • 框架: scrapy, pyspier.
  • url去重: bloomfilter
  • 图片处理: Pillow
  • OCR: Google 的 OCR 开源库 tesseract,对应的Python包是pytesser.
  • 代理: 代理Tor, PySocks
  • 消息队列: rabbitmq

###如何异步爬取?
可以使用grequests库,或者对于简单的爬虫,tornado文档有个demo,稍微改下自己用。
一个简单的异步爬虫类:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import time
from datetime import timedelta
from tornado import httpclient, gen, ioloop, queues
import traceback


class AsySpider(object):
    """A simple class of asynchronous spider."""
    def __init__(self, urls, concurrency=10, **kwargs):
        urls.reverse()
        self.urls = urls
        self.concurrency = concurrency
        self._q = queues.Queue()
        self._fetching = set()
        self._fetched = set()

    def fetch(self, url, **kwargs):
        fetch = getattr(httpclient.AsyncHTTPClient(), 'fetch')
        return fetch(url, **kwargs)

    def handle_html(self, url, html):
        """handle html page"""
        print(url)

    def handle_response(self, url, response):
        if response.code == 200:
            self.handle_html(url, response.body)

        elif response.code == 599:    # retry
            self._fetching.remove(url)
            self._q.put(url)

    @gen.coroutine
    def get_page(self, url):
        try:
            response = yield self.fetch(url)
            print('######fetched %s' % url)
        except Exception as e:
            print('Exception: %s %s' % (e, url))
            raise gen.Return(e)
        raise gen.Return(response)

    @gen.coroutine
    def _run(self):
        @gen.coroutine
        def fetch_url():
            current_url = yield self._q.get()
            try:
                if current_url in self._fetching:
                    return

                print('fetching****** %s' % current_url)
                self._fetching.add(current_url)

                response = yield self.get_page(current_url)
                self.handle_response(current_url, response)    # handle reponse

                self._fetched.add(current_url)

                for i in range(self.concurrency):
                    if self.urls:
                        yield self._q.put(self.urls.pop())

            finally:
                self._q.task_done()

        @gen.coroutine
        def worker():
            while True:
                yield fetch_url()

        self._q.put(self.urls.pop())    # add first url

        # Start workers, then wait for the work queue to be empty.
        for _ in range(self.concurrency):
            worker()

        yield self._q.join(timeout=timedelta(seconds=300000))
        assert self._fetching == self._fetched

    def run(self):
        io_loop = ioloop.IOLoop.current()
        io_loop.run_sync(self._run)


class MySpider(AsySpider):

    def fetch(self, url, **kwargs):
        """重写父类fetch方法可以添加cookies,headers,timeout等信息"""
        cookies_str = "PHPSESSID=j1tt66a829idnms56ppb70jri4; pspt=%7B%22id%22%3A%2233153%22%2C%22pswd%22%3A%228835d2c1351d221b4ab016fbf9e8253f%22%2C%22_code%22%3A%22f779dcd011f4e2581c716d1e1b945861%22%7D; key=%E9%87%8D%E5%BA%86%E5%95%84%E6%9C%A8%E9%B8%9F%E7%BD%91%E7%BB%9C%E7%A7%91%E6%8A%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8; think_language=zh-cn; SERVERID=a66d7d08fa1c8b2e37dbdc6ffff82d9e|1444973193|1444967835; CNZZDATA1254842228=1433864393-1442810831-%7C1444972138"
        headers = {
            'User-Agent': 'mozilla/5.0 (compatible; baiduspider/2.0; +http://www.baidu.com/search/spider.html)',
            'cookie': cookies_str
        }
        return super(MySpider, self).fetch(
            url, headers=headers, request_timeout=1
        )

    def handle_html(self, url, html):
        print(url, html)


def main():
    urls = []
    for page in range(1, 100):
        urls.append('http://www.baidu.com?page=%s' % page)
    s = MySpider(urls)
    s.run()


if __name__ == '__main__':
    main()

###如何模拟成浏览器?
使用requests库可以很方便的给请求加上header,具体可以参考requests的文档。


###如何提交表单?模拟登录
一般是查找html源代码找到form,然后看form提交的地址,就可以直接使用requests的post方法提交数据。
另外requests还有个Session模块,使用起来很方便。
有些网站如果是需要登录的,我们可以直接把登录后自己的cookies复制下来,直接作为requests的cookies参数传进去。


###如何模拟成搜索引擎?

1
2
3
4
5
6
# 模仿百度蜘蛛
# 模拟成搜索引擎只需要改下header的User-Agent,比如模拟百度爬虫:
headers = {
'User-Agent': 'Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)',
}
r = requests.get(url, headers=headers)

其他常见搜索引擎:
Baiduspider:
Mozilla/5.0 (compatible; Baiduspider/2.0; + http://www.baidu.com/search/spider.html)

Googlebot:
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)


###如何抓取手机app的内容?
手机内容一般通过发送请求使用json等数据格式通信,所以可以使用抓包软件fiddle等来抓取请求,分析请求来源,之后就可以模拟
发送请求抓取数据。抓包也可以使用mitmproxy,一个python开发的强大的代理软件,只需要用命令行启动mitmproxy,之后将手机wifi
代理更改成为电脑的ip和mitmproxy启动时指定的端口号,就可以看到app发送的请求了。接下来要做的就是仔细过滤请求,看看需要的
信息是通过什么请求发送的,我们就可以直接使用requests手工模拟获取数据了。


###碰到验证码怎么办?
上边提到过一个OCR库Tesseract, 简单的验证码可以使用这个命令行工具搞定.


###遇到动态生成的内容怎么办?
一种方法是打开浏览器的开发者工具,追踪到浏览器发送的请求,然后直接模拟。
还有一种方法是Selenium+PhantomJs库,具体可以参考网上的教程或者附录参考书。

#Ref
Web Scraping with Python