Scrapy爬取起点网小说应用ItemLoader类

第一步
刚开始我们先创建项目,在控制台输出:scrapy startproject qidihot_itemloader
当我们控制台返回这个 ,说明你创建成功了。
在这里插入图片描述
下面进行第二步
在这里插入图片描述
在这个文件夹里新建我们的.py文件 ,文件名为 qidihot_itemloader
下面先在items.py里进行变量的声明。

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class QidihotItemloaderItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    author=scrapy.Field()
    type=scrapy.Field()
    form=scrapy.Field()
    # pass

声明完成后,进行下面的qidihot_itemloader.py编写

from scrapy import Request
from scrapy.spiders import Spider
from scrapy.loader import ItemLoader #导入我们ItemLoader类
from qidihot_itemloader.items import QidihotItemloaderItem #引入我们的声明变量类

class HotSalesSpider(Spider):
    # 定义爬虫 名
    name='hot'
    current_page=1
    def start_requests(self):
        # 爬取目标url
        url='https://www.qidian.com/rank/hotsales?style=1'

        yield Request(url,callback=self.qidian_parse)
    def qidian_parse(self,response):
        list_selector=response.xpath('//*[@class="book-mid-info"]')
        for one_slector in list_selector:
            # 生成ItemLoader的实例
            # 参数item接收QidihotItemloaderItem实例,selector接收一个选择器
            novel=ItemLoader(item=QidihotItemloaderItem(),selector=one_slector)
            # 利用xpath获取小说名
            novel.add_xpath('name','h4/a/text()')
            # 利用xpath获取作者
            novel.add_xpath('author','p[1]/a[1]/text()')
            # 利用xpath获取类型
            novel.add_xpath('type','p[1]/a[2]/text()')
            #利用css选择器获取小说形式,(连载还是完本)
            novel.add_css('form','.author span::text')
            # 将提取好的数据 load出来,并使用yield返回
            yield novel.load_item()
        self.current_page+=1
        if self.current_page <=5:
            next_url='https://www.qidian.com/rank/hotsales?style=1&page=%d'%(self.current_page)
            yield Request(next_url,callback=self.qidian_parse)

当都写完成即可运行,在控制台输出 scrapy crawl hot -o hot.csv
hot:是你在name='hot’的爬虫 名
-o hot.csv是输出成hot.csv
在这里插入图片描述

这个就是我们的数据 以上就是scrapy的数据爬取ItemLoader类
人生苦短,我用python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值