场景1的实现:
创建爬虫爬虫文件:
- cd project_name(进入项目目录)
- scrapy genspider 爬虫文件的名称(自定义一个名字即可) 起始url
- (例如:scrapy genspider first www.xxx.com)
- 创建成功后,会在爬虫文件夹下生成一个py的爬虫文件
进入爬虫文件:
-
cd 爬虫文件的名称(即自定义的名字)
-
数据指纹:
- 数据的唯一标识。记录表中可以不直接存储数据本身,直接存储数据指纹更好一些。
可能存在的错误
redis.exceptions.DataError: Invalid input of type: 'ZlsdemoproItem'. Convert to a bytes, string, int or float first.
#只有redis版本是2.10.6才能直接把item作为字典写进去
redis可能用到的指令
keys * :查看redis数据库所有set集合名
llen 集合名:查看当前数据的数量(计数)
smembers 集合名:查看当前set集合内的数据id及名称
爬虫文件
import redis
import scrapy
import hashlib#导入生成数据指纹的模块
from ..items import ZlsdemoproItem #导入ITEM模块
class DuanzaiSpider(scrapy.Spider):
name = "duanzai"
# allowed_domains = ["www.xxx.com"]
#段子网爬取标题和内容
start_urls = ["https://www.xiaohuaduanzi.cn/duanzi/"]
conn = redis.Redis(
host = '127.0.0.1',
port = 6379
) #redis所对应的全局对象
def parse(self, response):
li_list = response.xpath('//*[@id="body"]/div/div/div[1]/ul/li')
for li in li_list:
content = li.xpath('./div/div/div[2]/div[2]/text()').extract_first()
title = li.xpath('./div/div/div[2]/div[1]/h2/a/text()').extract_first()
# print(content,title)
all_data = title + content
m = hashlib.md5() #生成该数据的数据指纹工具
m.update(all_data.encode('utf-8')) #数据编码,把字符串转成二进制数据
data_id = m.hexdigest() #生成数据结构
# print(data_id)
ex = self.conn.sadd('data_id', data_id) #在redis中创建名为data_id的set集合,并将data_id传递到该集合中
if ex ==1:#sadd执行成功(数据指纹在set集合中不存在)
print('已获取最新数据,正在爬取中.....')
item = ZlsdemoproItem() # 实例化ITEM对象
item['title'] = title # 将title传递给item
item['content'] = content # 将content传递给item
yield item #提交item
else:#sadd没有执行成功(数据指纹在set集合中已存储)
print('暂无最新数据更新,请等待数据更新!')
items.py
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class ZlsdemoproItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
content = scrapy.Field()
pipelines.py
# 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
class ZlsdemoproPipeline:
def process_item(self, item, spider):
conn = spider.conn #调用爬虫文件中的conn对象
dic = {
'title' : item['title'],
'content' : item['content'],
}
#保证redis版本是2.10.6 pip install redis==2.10.6
# 只有redis版本是2.10.6才能直接把item作为字典写进去
conn.lpush('duanzi',dic)
return item
settings.py
USER_AGENT : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
ROBOTSTXT_OBEY = False
LOG_LEVEL = 'ERROR'
LOG_LEVEL = 'WARNING'
#释放管道
ITEM_PIPELINES = {
"zlsDemoPro.pipelines.ZlsdemoproPipeline": 300,
}
标签:22,title,redis,爬虫,item,scrapy,22.1,div,Day
From: https://www.cnblogs.com/dream-ze/p/17144501.html