首页 > 解决方案 > Scrapy - 如何避免再次抓取同一页面

问题描述

我有非常简单的网站,有两种爬网路径。
主页https://amazn.com/list?page=1列出所有产品
,每个产品都有一个url指向详细信息页面的链接https://amzn.com/details/4ecf-wewe-adad-add3

class EcomSpider(scrapy.Spider):
    name = 'ecom_spider'
    allowed_domains = ['amazn.com']
    start_urls = ['https://amazn.com/list?page=1']

    def parse(self, response):
        for item in response.xpath('.//div/'):
            title = item.xpath('.//p[@class="title"]")]/text()').get()
            price = item.xpath('.//span[@class="price"]/text()').get()
            url = response.urljoin(item.xpath('.//h3//a/@href').get())

            item_main = {
                'title': title,
                'price': price
                'url': url,
            }

            yield scrapy.Request(url=url, callback=self.parse_details, meta={'item_main': item_main})

            next_page = response.xpath('//a[@class="pagination"]').get()
            if next_page is not None:
                next_page_url = response.xpath('//a[@class="pagination"]/@href').get()
                print("next page url", next_page_url)
                yield scrapy.Request(url=next_page_url, callback=self.parse)

    def parse_details(self, response):
        item_main = response.meta['item_main']
        item_main['description'] = response.xpath('//div[@class="description"]/text()').get()
        year = response.xpath('//div[@class="year"]/text()').get()
        
        yield item_main

并将结果保存到 CSV 文件

这里的问题是主页/list?page=1每天都会更新新产品,所以第二天当我运行爬虫时,它会找到相同的产品,/list?page=2而不是/list?page=1将重复的产品保存到 CSV 文件中。

我听说JOBDIR将 URL 存储为 sha1 以及它在我的场景中是如何工作的。scrapy框架中还有其他可用的设置吗?

我对避免爬取以前爬过的路线特别感兴趣,/details/因为/details/包含大约100K pages并且数据永远不会改变并且/list大约为 1K。

标签: scrapy

解决方案


推荐阅读