Python爬虫之增量式爬虫

相关介绍

增量式爬虫是一种用于爬取网页信息的技术,它与全量式爬虫相比具有更高效和节省资源的特点。

增量式爬虫的基本原理是通过比较已爬取的数据和新爬取的数据,只爬取和更新最新的数据。它会记录上一次爬取的状态,将新爬取的数据和已有的数据进行匹配和对比,只提取出新数据并进行存储。

增量式爬虫的优势在于可以减少对目标网站的访问次数和资源消耗,同时也能够保证数据的及时更新。它能够根据需求定制爬取规则,从而提高爬取的效率和精确度,减少重复爬取的数据。

增量式爬虫一般包括以下几个步骤:

  1. 初始化:设置爬取的起始点和爬取规则。

  2. 爬取网页:按照规定的规则和策略爬取网页内容,并将爬取的数据存储到数据库中。

  3. 数据对比和更新:将新爬取的数据与已有的数据进行对比,判断是否是新的数据。如果是新数据,则进行存储更新。

  4. 持续爬取:根据设定的规则和策略,定时或定量地进行持续的爬取和更新。

通过增量式爬虫,可以实现对目标网站数据的高效爬取和及时更新,提高了爬取的效率和精确度,减少了资源的浪费和重复爬取的数据量。

项目案例实战

前言:

本次案例基于Scrapy的CrawlSpider快速爬取,以及Scrapy-Redis的数据储存,来爬取电影网站标题和详情介绍

eight.py为开始创建CrawlSpider的项目名,其余全部自动生成

全部所需文件:

eight.py文件代码

python 复制代码
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from redis import Redis
from eightBlood.items import EightbloodItem


class EightSpider(CrawlSpider):
    name = "eight"
    # allowed_domains = ["www.baidu.com"]
    start_urls = ["http://kan.znds.com/movie/"]

    # 根据每个url规律写出正则表达式
    rules = (Rule(LinkExtractor(allow=r"p_\d+"), callback="parse_item", follow=False),)

    # 连接Redis数据库
    conn=Redis(host='127.0.0.1',port=6379)

    # 解析每个页码对应页面中电影的url
    def parse_item(self, response):
       div_list=response.xpath("/html/body/section[3]/div")
       # 获取详情页的url
       for div in div_list:
           detail_url="http://kan.znds.com"+div.xpath("./a/@href").extract_first()

           # 将爬取的每个电影详情页url存储到redis的urls中
           ex=self.conn.sadd('urls',detail_url)

           # 对是否爬取过的数据进行判断
           if(ex==1):
               print("该url没有被爬取过,可以进行数据的爬取")
               yield scrapy.Request(url=detail_url,callback=self.parse_detail)
           else:
               print("数据还没更新,暂时无数据可以爬取!")

    # 保存爬取的电影名和电影描述到item中
    def parse_detail(self, response):
        item=EightbloodItem()
        item['name']=response.xpath("/html/body/section[2]/div[2]/article/h1/a/text()").extract_first()
        item['desc']=response.xpath("/html/body/section[3]/span/p/text()").extract()
        item['desc']=''.join(item['desc'])
        yield item;

items.py文件

python 复制代码
import scrapy


class EightbloodItem(scrapy.Item):
    name= scrapy.Field()
    desc = scrapy.Field()
复制代码
pipelines.py文件
python 复制代码
from itemadapter import ItemAdapter

class EightbloodPipeline:
    conn=None
    def open_spider(self,spider):
        self.conn=spider.conn

    def process_item(self, item, spider):
        data={
            'name':item['name'],
            'desc':item['desc']
        }

        # 输出字典对象
        print(data)
        self.conn.lpush('MovieData',str(data))
        return item

setting.py文件设置

python 复制代码
ROBOTSTXT_OBEY = False

LOG_LEVEL='ERROR'

USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0"

ITEM_PIPELINES = {
   "eightBlood.pipelines.EightbloodPipeline": 300,
}

运行项目:

打开redis服务器

cmd打命令行cd 项目,输入scrapy crawl eight

运行过程:

运行结果:

相关推荐
顾林海4 小时前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱7 小时前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
Caco_D10 小时前
一行代码抓遍全网 20 个热榜!Aneiang.Pa 4.0 发布 — 极简 .NET 爬虫库
爬虫·.net
曲幽11 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码12 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱21 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵1 天前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio1 天前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户0332126663671 天前
使用 Python 从零创建 Word 文档
python
Csvn1 天前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python