ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Scrapling Spider 如何开启 development_mode 本地缓存响应并免真实请求反复调试

Scrapling Spider 如何开启 development_mode 本地缓存响应并免真实请求反复调试 Scrapling Spider 如何开启 development_mode 本地缓存响应并免真实请求反复调试【免费下载链接】Scrapling️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!项目地址: https://gitcode.com/GitHub_Trending/sc/Scrapling在调试 Scrapling 爬虫的parse()逻辑时每改一次选择器就得重新发起一轮真实请求慢而且给目标服务器带来噪音。Scrapling 的 Spider 系统提供了 Development Mode在 Spider 类上设置development_mode True后首次运行会把每个响应缓存到磁盘之后的运行全部从磁盘回放整个过程不发出任何网络请求。适用前提是你已经会创建和运行基本 Spidername、start_urls、parse()三件套。开启 development_mode在 Spider 类上把development_mode置为True。该属性默认为False不开启时引擎不会创建任何缓存管理器from scrapling.spiders import Spider, Response class QuotesSpider(Spider): name quotes start_urls [https://quotes.toscrape.com] development_mode True async def parse(self, response: Response): for quote in response.css(div.quote): yield { text: quote.css(span.text::text).get(), author: quote.css(small.author::text).get(), }运行方式与普通爬虫一致实例化后调用start()它内部处理了所有异步细节result QuotesSpider().start()首次运行与后续运行如何用 stats 验证回放生效Development Mode 的工作方式是首次运行正常发起网络请求并把每个响应存到磁盘。之后的每次运行对相同的请求直接从缓存取回完全跳过网络。引擎在每个响应上有两个额外的统计计数器用来观察缓存表现cache_hits和cache_misses。缓存命中的请求同样会计入requests_count、response_bytes和按状态码的计数所以统计输出和正常抓取看起来一致。验证方式就是跑两次后对比这两个值result QuotesSpider().start() stats result.stats print(fCache hits: {stats.cache_hits}) print(fCache misses: {stats.cache_misses})第一次运行所有请求都是缓存未命中cache_misses对应全部请求数。第二次运行请求全部命中缓存cache_hits对应全部请求数不再产生网络请求。另外引擎在启用 development mode 时会输出一条 warning 日志Development mode enabled -- responses will be cached to disk and replayed on subsequent runs看到它说明模式确实被激活了。回放时的具体行为命中缓存后引擎跳过网络请求的整条路径包括download_delay、限速以及is_blocked()触发的重试逻辑缓存的响应直接进入你的回调。缓存位置与自定义默认情况下响应缓存在.scrapling_cache/{spider.name}/注意这个路径是相对于你运行爬虫时所在的工作目录而不是 Spider 脚本所在的目录。存储格式为每个响应一个 JSON 文件文件名为{fingerprint_hex}.json响应体经 base64 编码以完整保留二进制内容写入是原子的临时文件 重命名。如果想把缓存放到别的位置比如不想污染工作目录用development_cache_dir类属性覆盖class QuotesSpider(Spider): name quotes start_urls [https://quotes.toscrape.com] development_mode True development_cache_dir /tmp/quotes_spider_cache async def parse(self, response: Response): ...让缓存失效改变指纹与手动清理理解缓存键的规则才能判断改了什么会导致重新抓取缓存键是请求的 fingerprint。因此修改任何影响指纹的 Spider 属性fp_include_kwargs、fp_include_headers、fp_keep_fragments三者默认均为False都会使缓存键变化从而产生全新的抓取而不是回放旧缓存。这些属性在 Requests Responses 文档中有说明。缓存没有自动过期机制。要强制全新抓取删除缓存目录或调用缓存管理器的clear()方法。限制文档明确提醒Development Mode 只用于开发不用于生产。缓存的响应永不过期且回放会绕过限速和被请求拦截时的重试路径。所以不要带着development_mode True发布 Spider——调试完成后把该属性改回False或删除该属性再投入正式使用。更多 Spider 高级特性并发控制、Pause Resume、Streaming、生命周期钩子可参考 Advanced usages 中的 Development Mode 章节及相邻章节。【免费下载链接】Scrapling️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!项目地址: https://gitcode.com/GitHub_Trending/sc/Scrapling创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表