pyspider爬取网页

开启爬虫

pyspider
#后台启动pyspider
pyspider all &

还是爬取之前那个动漫网站做对比,pyspider最大的好处是调试非常方便,只是爬取速度没得前面的快

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2018-06-03 21:52:13
# Project: test

from pyspider.libs.base_handler import *


class Handler(BaseHandler):
    crawl_config = {
    }

    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl('http://www.mmonly.cc/ktmh/hzw/list_34_1.html', callback=self.index_page)

    @config(age=10 * 24 * 60 * 60)
    def index_page(self, response):
        #下一页
        for each in response.doc('.title a').items():
            self.crawl(each.attr.href, callback=self.detail)
        #抓取内容页
        url = response.doc('#pageNum > a:nth-last-child(2)').attr.href
        if url:
            self.crawl(url, callback=self.index_page) 

    @config(age=10 * 24 * 60 * 60)
    def detail(self, response):
        #详情页面
        #print response.doc('#contbody > div > div > a > img').attr('src')
        self.crawl(response.url+'?time=1', callback=self.detail_page) 
        #其他页面
        next_url = response.doc('#nl a').attr.href
        #print next_url
        #for each in response.doc('.pages a:last').items():
        if next_url != None and not next_url.endswith('##'):
            self.crawl(next_url, callback=self.detail)

    @config(priority=2)
    def detail_page(self, response):
        return {
            "img": response.doc('p img').attr('src')
        }

代码简单分析:
- def on_start(self) 方法是入口代码。当在web控制台点击run按钮时会执行此方法。
- self.crawl(url, callback=self.index_page)这个方法是调用API生成一个新的爬取任务,这个任务被添加到待抓取队列。
- def index_page(self, response) 这个方法获取一个Response对象。 response.doc是pyquery对象的一个扩展方法。pyquery是一个类似于jQuery的对象选择器。
- def detail_page(self, response)返回一个结果集对象。这个结果默认会被添加到resultdb数据库(如果启动时没有指定数据库默认调用sqlite数据库)。你也可以重写on_result(self,result)方法来指定保存位置。

更多知识:
- @every(minutes=24*60, seconds=0) 这个设置是告诉scheduler(调度器)on_start方法每天执行一次。
- @config(age=10 * 24 * 60 * 60) 这个设置告诉scheduler(调度器)这个request(请求)过期时间是10天,10天内再遇到这个请求直接忽略。这个参数也可以在self.crawl(url, age=10*24*60*60) 和 crawl_config中设置。
- @config(priority=2) 这个是优先级设置。数字越大越先执行。

别人配置好的一个爬虫测试库:http://demo.pyspider.org/
参数文档参考

猜你喜欢

转载自blog.csdn.net/qq_35641192/article/details/80561141