【Python3.4.3】Scrapy1.2.0网络爬虫使用CrawlSpider抓取整站内容(二)

来源:赵克立博客 分类: Python 标签:Python网络爬虫Scrapy发布时间:2016-12-04 20:14:33最后更新:2017-10-05 14:04:58浏览:2795
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-10-05 14:04:58
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

scrapy.spiders.Spider是Scrapy框架最核心部分之一,然而我们最常用的是爬取某一个网站的内容,这个时候我们可能就需要用到下面这个类啦 CrawlSpider,开始之前要先定义好想提取的对应的item,不会定义item的可以参考这篇文章 Scrapy1.2.0网络爬虫使用入门(一)

看下面代码爬取所有文章信息

# -*- coding: utf-8 -*-
import scrapy
from blog.items import ArticleItem
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class AllarcSpider(CrawlSpider):
    name = "allarc"
    allowed_domains = ["zhaokeli.com"]
    #定义一个或多个入口地址
    start_urls = (
        "http://www.xxxx.com",
        "http://www.xxxx.com/2.html",
    )
    rules = (
    # 提取匹配 含有内容列表的页面链接并跟进链接(没有callback意味着follow默认为True)
    Rule(
        LinkExtractor(allow=('arc/list\.html','tag_list.html', ),),
        ),
    # 提取内容页并且传到回调里处理数据
    Rule(
        LinkExtractor(allow=('article/\d*?\.html', ),),
        callback='parse_item',
         ),
    )
    def parse_item(self, response):
        self.log('Hi, this is an item page! %s' % response.url)
        items=[]
        item =  ArticleItem()
        item['title'] = response.xpath('//h1/text()').extract()
        item['link'] = response.xpath('/html/body/div[2]/div[2]/article/div[3]/a/@href').extract()
        print(item)
        items.append(item)
        return items

这里面最关键的就是rules这里面的规则啦,这里要注意下,可能你爬取到很多页面但数据却是空的可能就是这个规则定义的不正确 rules 是一个包含一个(或多个) Rule 对象的集合(list)。 每个 Rule 对爬取网站的动作定义了特定表现。 如果多个rule匹配了相同的链接,则根据他们在本属性中被定义的顺序,第一个会被使用。更多的信息可以参考中文手册

http://scrapy-chs.readthedocs.io/zh_CN/0.24/topics/spiders.html#crawling-rules


爬取结束会显示请求的次数下载的总字节等信息


blob.png


微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python