Python爬虫入门-小试CrawlSpider

首先,先转载一张原理图:

[转载]CrawlSpider原理图.png

再贴一下官方文档的例子:

import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

class MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

    rules = (
        # 提取匹配 'category.php' (但不匹配 'subsection.php') 的链接并跟进链接(没有callback意味着follow默认为True)
        Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),

        # 提取匹配 'item.php' 的链接并使用spider的parse_item方法进行分析
        Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
    )

    def parse_item(self, response):
        self.log('Hi, this is an item page! %s' % response.url)

        item = scrapy.Item()
        item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
        item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
        item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
        return item

再贴一下重要参数:

Rule:(
      link_extractor               #定义链接提取的规则
      callback=None                #回调函数(不可使用parse方法)
      cb_kwargs=None               #传递关键字参数给回调函数的字典
      follow=None                  #是否跟进,
      process_links=None           #过滤linkextractor列表,每次获取列表都会调用
      process_request=None         # 过滤request,每次提取request都会调用
)
[此处为转载]follow说明:指定了根据link_extractor规则从response提取的链接是否需要跟进,跟进的意思就是指让CrawlSpider对这个提取的链接进行处理,继续拿到该链接的Response,然后继续使用所有的rule去匹配和提取这个Response,然后再不断的做这些步骤。callback为空时,follow默认为true,否则就是false。


LinkExtractor:(
      allow=()              #满足括号中所有的正则表达式的那些值会被提取,如果为空,则全部匹配
      deny=()               #满足括号中所有的正则表达式的那些值一定不会被提取。优先于allow参数。
      allow_domains=()      #会被提取的链接的域名列表
      deny_domains=()       #一定不会被提取链接的域名列表
      restrict_xpath=()     #限制在哪个结构中提取URL
      tags=()               #根据标签名提取数据 
      attrs=()              #根据标签属性提取数据
      .
      .
      .
)

造轮子的是用豆瓣读书/所有热门标签,所需要的信息都能在原始的请求中得到:

分析-00.png

我们所看到的这些标签都是在【div[class=”article”]】结构里面,再者这些标签的URL结构都是:【/tag/XX】:

分析-01.png

据此可以构建:

Rule(LinkExtractor(allow('/tag/'),restrict_xpaths('//div[@class="article"]')),follow=True)

点击小说标签,进入到相关的页面,我们要获取所有的链接,由于有多页,所以就要实现一个翻页的操作,获得所有的链接:

分析-02.png

通过审查元素,可以看出页码都是在【div[@class=”paginator”]】结构里面,再者这些页码的URL结构都是:【\?start=\d+\&type=】:

分析-03.png

据此可以构建:

Rule(LinkExtractor(allow('\?start=\d+\&type='),restrict_xpaths('//div[@class="paginator"]')),follow=True)

最终,就可以进入到详情页面中提取我们想要的信息了,详情页都是在【ul[@class=”subject-list”]】结构里面,再者这些页码的URL结构都是:【/subject/\d+/$】:

分析-04.png

Rule(LinkExtractor(allow=('/subject/\d+/$'),restrict_xpaths=('//ul[@class="subject-list"]')),callback='parse_item')

详情页感觉还是不好提取,我就提取了几个简单的,有兴趣的可以自己试试多提取点内容。

from scrapy.spider import CrawlSpider,Rule
from scrapy.linkextractors import LinkExtractor
from dbdushu.items import DbdushuItem


class DoubanSpider(CrawlSpider):
    Num=1
    name = 'douban'
    # allowed_domains = ['www.douban.com']
    start_urls = ['https://book.douban.com/tag/?view=type&icn=index-sorttags-all']
    rules=(
        Rule(LinkExtractor(allow=('/tag/'),restrict_xpaths=('//div[@class="article"]')),follow=True),
        Rule(LinkExtractor(allow=('\?start=\d+\&type='),restrict_xpaths=('//div[@class="paginator"]')),follow=True),
        Rule(LinkExtractor(allow=('/subject/\d+/$'),restrict_xpaths=('//ul[@class="subject-list"]')),callback='parse_item'),
    )

    def parse_item(self, response):
        print('==========正在处理:#%r =========='%self.Num)
        self.Num=self.Num+1
        item=DbdushuItem()
        item['link']=response.url
        item['title']=response.xpath('//*[@id="wrapper"]/h1/span/text()').extract_first().strip()
        if response.xpath('//*[@id="info"]/span[1]/a'):
            item['author']=''.join(response.xpath('//*[@id="info"]/span[1]/a/text()').extract()).strip()
        if response.xpath('//*[@id="info"]/a[1]'):
            item['author']=''.join(response.xpath('//*[@id="info"]/a[1]/text()').extract()).strip()
        item['score']=response.xpath('//*[@id="interest_sectl"]/div/div[2]/strong/text()').extract_first(default='No Found').strip()
        yield item

结果就保存在Mongodb,上次爬用手机号注册了个账号想怕电影评论,没几分钟就直接账号永久被封,实在是傻眼了。这个下载延迟刚开始设置了1.5s,爬了一会觉得太慢了,于是修改成了0.8s,过一会就要求输入验证码了,应该还是太快了,最后还是修改成了1.5s,心累:

运行-02.png

一万多本了,不想爬了:

运行-03.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值