第一步
刚开始我们先创建项目,在控制台输出: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