mlhz

需求 想要爬去糗事百科全站的数据

方法:

(1)基于Scrapy框架中的Spider的递归爬去实现

(2) 基于Scrapy框架的CrawlSpider的自动爬取来进行实现

那么CrawlSpider又是什么呢?如何实现它的自动爬取?

CrawlSpider的简介

一 简介

crawlspider是spider的一个子类,除了继承到Spider的功能外,还派生了其自己的更强大的功能和特性。其中最显著的功能就是\'”LinkExtractors链接提取器\'。Spider是所有怕爬虫类的基类

二 使用

步骤:

(1)创建scrapy工程:scrapy startproject projectName

(2) 创建爬虫文件:scrapy genspider -t crawl spidername www.xxx.com

注意 这里创建爬虫文件时比之前创建的爬虫文件多了-t crawl 表示的时创建的爬虫文件是一个基于CrawlSpider这个类,而不是Spider这个基类了

(3)生成的爬虫文件和之前的spider基类的爬虫文件有所不同

需求 爬取到抽屉网站中分页中的url

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

#爬取抽屉网站的分页的URL
#注意 这里继承的类是CrawlSpider  而不是Spider
class ChoutiSpider(CrawlSpider):
    name = \'chouti\'
    # allowed_domains = [\'www.xxx.com\']
    start_urls = [\'https://dig.chouti.com/r/scoff/hot/1\']
    #allow表示链接提取器提取链接的规则
    rules = (
        #Rule  规则提取器:将链接提取器提取到的链接所对应的页面进行指定形式的解析
        #follow 让连接提取器继续作用到链接提取器提取到的链接所对应的页面中
        Rule(LinkExtractor(allow=r\'/r/scoff/hot/\d+\'), callback=\'parse_item\', follow=True),
    )

    def parse_item(self, response):
        print(response)
        item = {}
        item[\'domain_id\'] = response.xpath(\'//input[@id="sid"]/@value\').get()
        item[\'name\'] = response.xpath(\'//div[@id="name"]\').get()
        item[\'description\'] = response.xpath(\'//div[@id="description"]\').get()
        return item

需求 爬取糗事百科网站的分页的URL

#爬取糗事百科网站的分页的URL
class ChoutiSpider(CrawlSpider):
    name = \'qiubai\'
    # allowed_domains = [\'www.xxx.com\']
    start_urls = [\'https://www.qiushibaike.com/pic/\']
    #allow表示链接提取器提取链接的规则
    link = LinkExtractor(allow=r\'/pic/page/\d+\?s=\d+\')
    link1 = LinkExtractor(allow=r\'/pic/$\')
    #注意这里可以有多个规则
    rules = (
        #Rule  规则提取器:将链接提取器提取到的链接所对应的页面进行指定形式的解析
        #follow 让连接提取器继续作用到链接提取器提取到的链接所对应的页面中
        Rule(link, callback=\'parse_item\', follow=True),
        Rule(link1,callback=\'parse_item\',follow=True)
    )

    def parse_item(self, response):
        print(response)

分类:

技术点:

相关文章: