【scrapy】2.第一个scrapy爬虫项目

参考:python爬虫基础小案例, scrapy框架,思路和经验你全都有。_scrapy爬虫案例python-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/m0_65833575/article/details/124425545

目录

1.查看虚拟环境

2.切换已安装scrapy的虚拟环境

3.创建爬虫项目——scrapy startproject 项目名字

4.创建爬虫文件——scrapy genspider 爬虫文件的名字 "要爬取的网页URL"

5.定义数据结构——编辑items.py

6.编辑Spider中的爬虫代码——编辑爬虫文件

7.运行爬虫代码——scrapy crawl 爬虫名

8.解析数据——编辑爬虫文件

9.对数据进行封装——编辑爬虫文件,导入items类进行封装

 10.数据下载——pipelines.py

 11.打开管道——settings.py 文件

 12.运行scrapy 文件 


1.查看虚拟环境

# 查看已有的虚拟环境
conda info --envs
# 或者
conda env list

2.切换已安装scrapy的虚拟环境

# 在命令行中切换到想要的虚拟环境,我这里切换到sy1
conda activate sy1

3.创建爬虫项目

在python 中的终端中,创建scrapy框架

语法:scrapy startproject 项目名字

注意: 项目名字不能出现中文,也不能以数字开头

打开文件后,项目结构如下;

4.创建爬虫文件

在spiders文件夹中创建爬虫文件

cd 项目的名字\项目的名字\spiders

 进入spiders文件后创建爬虫文件:scrapy genspider 爬虫文件的名字 "要爬取的网页URL"

注:URL记得用 ” “包起来

创建成功:

5.定义数据结构

进入items.py

更改为:

import scrapy
  
class ScrapyDyttCsdnItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    
    #定义好数据结构
    name = scrapy.Field()   #书名
    author = scrapy.Field() #作者
    imgSrc = scrapy.Field() #图片
    price = scrapy.Field()  #价格
    pass

注:Field是Scrapy提供的用于定义Item字段的类。每个Field对象代表一个数据字段,它可以用来存储爬虫从网页中提取的数据。
#Field对象本身没有太多的功能,它主要用来声明Item的字段。规范数据结构&方便扩展和维护&与Pipeline集成

6.编辑Spider中的爬虫代码

 进入spiders文件下的  ddsp,

import scrapy
 
 
class DyttSpider(scrapy.Spider):
    name = 'ddsp'
    #链接范围,不在该范围内的url请求,都会报错,一般只写域名
    allowed_domains = ['e.dangdang.com']
    
#改一下strat 和 end 这两个是前面提过的 strat=0  和 end=20
#意思也就是从索引0开始,一直到索引20,也就是21本书
    start_urls = ['http://e.dangdang.com/media/api.go?action=mediaCategoryLeaf&promotionType=1&deviceSerialNo=html5&macAddr=html5&channelType=html5&permanentId=20220424124301850188613824148624365&returnType=json&channelId=70000&clientVersionNo=6.8.0&platformSource=DDDS-P&fromPlatform=106&deviceType=pconline&token=&start=0&end=20&category=QCWX&dimension=dd_sale&order=0']
 
    def parse(self, response):
#页面返回来的数据全在response 中,response.text 看看数据有没有获取到;默认是pass
        print(response.text)

7.运行爬虫代码

在python 中的终端中,语法:scrapy crawl 爬虫名

# 回到项目的根目录
cd C:\Users\whw\scrapy_01
# 运行爬虫
scrapy crawl ddsp

执行完毕后:

        

8.解析数据

数据杂乱,需要通过单个数据进行解析结构。

import scrapy
import json
 
class DyttSpider(scrapy.Spider):
    name = 'ddsp'
    #链接范围,不在该范围内的url请求,都会报错,一般只写域名
    allowed_domains = ['e.dangdang.com']
    
    start_urls = ['http://e.dangdang.com/media/api.go?action=mediaCategoryLeaf&promotionType=1&deviceSerialNo=html5&macAddr=html5&channelType=html5&permanentId=20220424124301850188613824148624365&returnType=json&channelId=70000&clientVersionNo=6.8.0&platformSource=DDDS-P&fromPlatform=106&deviceType=pconline&token=&start=0&end=20&category=QCWX&dimension=dd_sale&order=0']
 
    def parse(self, response):
        json_list = json.loads(response.text)
        #  json_list['data']['saleList']  获取每一本书的信息
 
        for i in json_list['data']['saleList']: #遍历每一本书 获取其中需要的数据
            author = i['mediaList'][0]["authorPenname"]
            imgSrc = i['mediaList'][0]["coverPic"]
            name = i['mediaList'][0]["title"]
            price =i['mediaList'][0]["lowestPrice"]
            print(author,name,imgSrc,price)

整理后,显示为:

9.对数据进行封装

把解析好的数据给 items.py 中的类,让items.py 给数据进行封装 dict 字典格式,

并将数据交给管道 pipelines.py 文件,进行下载。

import scrapy
import json
 
class DyttSpider(scrapy.Spider):
    name = 'ddsp'
    #链接范围,不在该范围内的url请求,都会报错,一般只写域名
    allowed_domains = ['e.dangdang.com']
    
    start_urls = ['http://e.dangdang.com/media/api.go?action=mediaCategoryLeaf&promotionType=1&deviceSerialNo=html5&macAddr=html5&channelType=html5&permanentId=20220424124301850188613824148624365&returnType=json&channelId=70000&clientVersionNo=6.8.0&platformSource=DDDS-P&fromPlatform=106&deviceType=pconline&token=&start=0&end=20&category=QCWX&dimension=dd_sale&order=0']
 
    def parse(self, response):
        json_list = json.loads(response.text)
        #  json_list['data']['saleList']  获取每一本书的信息
 
        for i in json_list['data']['saleList']: #遍历每一本书 获取其中需要的数据
            author = i['mediaList'][0]["authorPenname"]
            imgSrc = i['mediaList'][0]["coverPic"]
            name = i['mediaList'][0]["title"]
            price =i['mediaList'][0]["lowestPrice"]
            print(author,name,imgSrc,price)
            
            #这一过程增加了一下两步!!!!!!
            #导入items.py 中的类 也就是我们刚刚定义好的数据结构 会定义成一个字典格式的数据结构
            #从项目的items.py文件中导入了一个名为Scrapy01Item的类。
            from scrapy_01.items import Scrapy01Item
            # 创建了一个Scrapy01Item类的实例,名为book
            book = Scrapy01Item(author=author,imgSrc=imgSrc,name=name,price=price)
 
            #把数据交给管道 piplines.py  进行数据的下载
            yield book

 10.数据下载

进入 pipelines.py文件,定义【打开】【处理】【关闭】3个方法。

原文件为:

更改为:

from itemadapter import ItemAdapter


class Scrapy01Pipeline:
 
    #程序执行前第一个开始此方法,该方法是框架内置方法,方法名一定不能修改,否则会报错
    def open_spider(self,spider):
        #打开文件
        self.fp = open("book.json",'w',encoding='utf-8')
 
    def process_item(self, item, spider):
        #item 中就是 dytt.py 文件中 yield book 中返回的数据
        #注意 item 要转化成字符串类型,否则会报错
        self.fp.write(str(item))
        return item
 
    def closer_spider(self,spider):
        #关闭文件
        self.fp.close()

 11.打开管道

在settings.py 文件中打开管道,把指定行的注释解开,即含有【ITEM_PIPELINES】的这3行。

 12.运行scrapy 文件 

语法:scrapy crawl 爬虫文件的名字

最后文件book.json 文件会在 spiders文件夹下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值