如何在Scrapy CrawlSpider中找到当前的start_url?

问题描述 投票:0回答:1

当从一个自己的脚本运行Scrapy时,它从数据库加载URL并跟随这些网站上的所有内部链接,我遇到了一个小问题。我需要知道当前使用哪个start_url,因为我必须保持与数据库(SQL DB)的一致性。但是:当Scrapy使用名为“start_urls”的内置列表以便接收要遵循的链接列表并且这些网站立即重定向时,就会出现问题。例如,当Scrapy启动并且正在爬行start_urls并且爬虫跟随在那里找到的所有内部链接时,我稍后只能确定当前访问的URL,而不是Scrapy开始的start_url。

来自网络的其他答案是错误的,对于其他用例或被弃用,因为去年Scrapy的代码似乎发生了变化。

MWE:

from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.crawler import CrawlerProcess

class CustomerSpider(CrawlSpider):
    name = "my_crawler"
    rules = [Rule(LinkExtractor(unique=True), callback="parse_obj", ), ]

    def parse_obj(self, response):
        print(response.url)  # find current start_url and do something

a = CustomerSpider
a.start_urls = ["https://upb.de", "https://spiegel.de"]  # I want to re-identify upb.de in the crawling process in process.crawl(a), but it is redirected immediately  # I have to hand over the start_urls this way, as I use the class CustomerSpider in another class
a.allowed_domains = ["upb.de", "spiegel.de"]

process = CrawlerProcess()

process.crawl(a)
process.start()

在这里,我提供了一个MWE,其中Scrapy(我的爬虫)收到一个URL列表,就像我必须这样做。示例redirection-url是https://upb.de,它重定向到https://uni-paderborn.de

我正在寻找一种处理这种方式的优雅方式,因为我想利用Scrapy的众多功能,例如并行爬行等。因此,我不想再使用类似于请求库的东西。我想找到目前在内部使用的Scrapy start_url(在Scrapy库中)。我感谢您的帮助。

python-3.x scrapy web-crawler scrapy-spider
1个回答
0
投票

理想情况下,您可以在原始请求上设置meta属性,稍后在回调中引用它。不幸的是,CrawlSpider不支持通过meta传递Rule(参见#929)。

你最好建立自己的蜘蛛,而不是继承CrawlSpider。首先将start_urls作为参数传递给process.crawl,这使它可以作为实例上的属性使用。在start_requests方法中,为每个URL生成一个新的Request,包括数据库密钥作为meta值。

parse通过加载你的网址收到响应时,在它上面运行一个LinkExtractor,并请求每个人单独抓取它。在这里,您可以再次传递meta,将原始数据库密钥传播到链中。

代码如下所示:

from scrapy.spiders import Spider
from scrapy import Request
from scrapy.linkextractors import LinkExtractor
from scrapy.crawler import CrawlerProcess


class CustomerSpider(Spider):
    name = 'my_crawler'

    def start_requests(self):
        for url in self.root_urls:
            yield Request(url, meta={'root_url': url})

    def parse(self, response):
        links = LinkExtractor(unique=True).extract_links(response)

        for link in links:
            yield Request(
                link.url, callback=self.process_link, meta=response.meta)

    def process_link(self, response):
        print {
            'root_url': response.meta['root_url'],
            'resolved_url': response.url
        }


a = CustomerSpider
a.allowed_domains = ['upb.de', 'spiegel.de']

process = CrawlerProcess()

process.crawl(a, root_urls=['https://upb.de', 'https://spiegel.de'])
process.start()

# {'root_url': 'https://spiegel.de', 'resolved_url': 'http://www.spiegel.de/video/'}
# {'root_url': 'https://spiegel.de', 'resolved_url': 'http://www.spiegel.de/netzwelt/netzpolitik/'}
# {'root_url': 'https://spiegel.de', 'resolved_url': 'http://www.spiegel.de/thema/buchrezensionen/'}
© www.soinside.com 2019 - 2024. All rights reserved.