欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > scrapy--json结构数据-存储

scrapy--json结构数据-存储

2024/10/25 11:33:44 来源:https://blog.csdn.net/2303_80857229/article/details/141501496  浏览:    关键词:scrapy--json结构数据-存储

免责声明:本文仅做演示与分享...

目录

基于命令存储的解析方法:

settings.py

blibli.py

基于管道存储的解析方法:

  1-在爬虫文件中进行数据解析

  2-在items.py定义相关属性

  3-在 爬虫文件中 把 解析的数据存储封装到item类型对象中

  4-把item类型对象提交给管道

  5-在管道文件中,接收爬虫文件提交过来的item类型对象

保存到Excel中:

保存到数据库(mysql)中:

 

  6-配置文件中开启管道


b站热度排行榜

基于命令存储的解析方法:

--只需修改图中画圈的文件即可.

settings.py

根据需要自己设置.

(伪装头,君子协议,日志输出)...

blibli.py

import scrapy
from scrapy_demo1.items import ScrapyDemo1Item# 找到数据所在的URL
# 执行项目
class BlibliSpider(scrapy.Spider):name = "blibli"# allowed_domains = ["blibli.com"]start_urls = ["https://api.bilibili.com/x/web-interface/ranking/v2?rid=0&type=all&web_location=333.934&w_rid=6d0af3cab734841a471545ef10d2a0f0&wts=1724383027"]# 基于命令存储的解析方法def parse(self, response):ls = []# pass# 如果请求的url的响应内容为json数据,也可以直接调用json()方法获取数据# print(response.json())  # 字典类型data = response.json()# print(data)for d in data["data"]["list"]:aid = d["aid"]desc = d["desc"]title = d["title"]name = d["owner"]["name"]# print(aid, desc, title, name)# 一次性返回100条数据, [{},{},{},{}]dict = {"视频id": aid,"视频标题": title,"视频描述": desc,"视频作者": name,}ls.append(dict)return ls

---返回一个对象之后,直接 scrapy crawl blibli -o blibli.csv 即可. 


基于管道存储的解析方法:

复杂点 -->

  1-在爬虫文件中进行数据解析

import scrapy
from scrapy_demo1.items import ScrapyDemo1Item# 找到数据所在的URL
# 执行项目
class BlibliSpider(scrapy.Spider):name = "blibli"# allowed_domains = ["blibli.com"]start_urls = ["https://api.bilibili.com/x/web-interface/ranking/v2?rid=0&type=all&web_location=333.934&w_rid=6d0af3cab734841a471545ef10d2a0f0&wts=1724383027"]# 基于管道存储的解析方法def parse(self, response):data = response.json()for d in data["data"]["list"]:aid = d["aid"]desc = d["desc"]title = d["title"]name = d["owner"]["name"]# 类名() ScrapyDemo1Item() 实例化item = ScrapyDemo1Item()# 把解析出来的数据存入到对象中: 对象名.属性名 = 数据# !!!!!!!!!!!# 不能按对象的属性添加. 而要放到字典中, 然后再把字典传给item对象.item["bvid"] = aiditem["title"] = titleitem["desc"] = descitem["name"] = name# 调用yield将数据传递给管道; return则不会传递给管道. return,yieldyield item  # 数据有多少条就提交多少次.

  2-在items.py定义相关属性

(你要保存什么数据,就定于什么属性.)

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass ScrapyDemo1Item(scrapy.Item):  # 类名可以自定义,但是必须继承scrapy.Item# define the fields for your item here like:# 类中定义属性,定义几个属性,取决于你bvid = scrapy.Field()  # 字段# 属性名可以自定义,建议和解析时的一样.title = scrapy.Field()desc = scrapy.Field()name = scrapy.Field()

  3-在 爬虫文件中 把 解析的数据存储封装到item类型对象中

 

  4-把item类型对象提交给管道

yield item  # 数据有多少条就提交多少次.

  5-在管道文件中,接收爬虫文件提交过来的item类型对象

  (默认的类只针对保存到txt里面.)

保存到 Excel / 数据库 中 需要自己定义类.

 

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html# useful for handling different item types with a single interface
from itemadapter import ItemAdapterclass ScrapyDemo1Pipeline:  # 如果自定义类名,在配置文件中也要修改.# 打开 , 写入 , 关闭.def open_spider(self, spider):print("爬虫开始")# 打开文件: 只能用 open# 添加属性:当对象中没有该属性时,才会添加.  修改属性:当对象中有f属性时.self.f = open("b站2.txt", "w", encoding="utf-8")def process_item(self, item, spider):  # item 是爬取的item, spider 是爬虫对象.# yield 提交多少次,就会执行多少次process_item函数.# print(1)# 保存到记事本文件中    w :覆盖模式   a :追加模式# 浪费资源 ---多次打开和关闭.# with open("b站.txt", "a", encoding="utf-8") as f:#     # item 不是字符串.  write() 方法需要字符串参数.self.f.write(f"{item['bvid']}\n{item['title']}\n{item['desc']}\n{item['name']}")return item  # 是否提交给下一个管道类 (优先级)# print(3)# pass# 一次打开,多次写入:def close_spider(self, spider):self.f.close()print("爬虫结束")

保存到Excel中:

后面的设置别忘了配置一下.

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html# useful for handling different item types with a single interface
from itemadapter import ItemAdapterimport openpyxl# 自定义管道类--保存到excel文件中.
class ExcelPipeline:# 创建工作薄对象 1# 选择工作表    1# 添加表头    1# 写入数据    多# 保存文件    1def open_spider(self, spider):self.wb = openpyxl.Workbook()self.sheet = self.wb.activeself.sheet.append(["视频id", "视频标题", "描述", "作者"])def process_item(self, item, spider):self.sheet.append([item["bvid"], item["title"], item["desc"], item["name"]])def close_spider(self, spider):self.wb.save("b站排行榜数据.xlsx")

保存到数据库(mysql)中:

后面的设置别忘了配置一下.

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html# useful for handling different item types with a single interface
from itemadapter import ItemAdapter# 保存到数据库中:
import pymysql# utf8mb4 解决表情包问题.
class MySQLPipeline:# 创建连接对象 1# 创建游标对象 1# 插入数据 多# 提交事务 1# 关闭游标 1# 关闭连接 1conn = ""cur = ""def open_spider(self, spider):# 连接数据库self.conn = pymysql.connect(host="127.0.0.1", user="root", password="root", port=3306, database="test")# 创建游标self.cursor = self.conn.cursor()def process_item(self, item, spider):try:# 插入数据sql = 'INSERT INTO blibli VALUES (NULL,"%s", "%s", "%s", "%s")' % (item["title"],item["desc"],item["bvid"],item["name"],)self.cursor.execute(sql)  # 执行后 出现有的数据插不进去,火星文.# 数据库中title字段默认使用的utf8 ,无法保存表情包,-->用utf8mb4.# 提交事务self.conn.commit()except Exception as e:print(sql)print(e)# 回滚事务self.conn.rollback()def close_spider(self, spider):if self.conn != "" and self.cur != "":# 关闭游标self.cursor.close()# 关闭连接self.conn.close()print("结束-------------")

 


  6-配置文件中开启管道


版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com