python - Scrapy - 在解析回调之外生成项目

标签 python scrapy

这可能有点奇怪。我有一个 Scrapy 项目,其中包含一些继承自 CrawlSpider 的蜘蛛。除了它们的正常执行(通过预期的网站),我还希望能够将项目推送到原始回调的范围之外

我定义了一个线程,它遍历文件夹中的文件,然后将它们传递给 parse_files,就好像它是由 Scrapy 下载的内容一样。有什么方法可以通过我拥有的管道和中间件获取从中生成的项目,就好像它只是另一个下载的页面一样?

我知道这不是他们想要的架构,但我想知道我是否可以解决这个问题。我熟悉 Scrapy 的架构,基本上是在寻找一种将项目推送到引擎的好方法。

class SomeSpider(CrawlSpider):
name = "generic_spider"

def __init__(self):
    CrawlSpider.__init__(self, instance_config)
    self.file_thread = Thread(target=self._file_thread_loop)
    self.file_thread.daemon = True
    self.file_thread.start()

    self.rules += (Rule(LxmlLinkExtractor(allow=['/somepath/'], deny=[], callback=self.parse_items, follow=True),)

def _file_thread_loop(self):
    while True:
    #... read files...
        for file in files:
            response = HtmlResponse(url=file['url'], body=file['body'])
            for item in self.parse_items(response):
                yield item # <-- I want this to go to the pipelines and middlewares

        time.sleep(10)


def parse_items(self, response):
    hxs = Selector(response)

    # ... parse page ...
    for item in resulting_items:
        yield item    

最佳答案

我不确定是否有办法将项目直接推送到引擎,但你可以做的是将虚拟请求与元变量中的项目一起推送,然后在回调中产生它们。

def _file_thread_loop(self):
    while True:
    #... read files...
        for file in files:
            response = HtmlResponse(url=file['url'], body=file['body'])
            req = Request(
                url='http://example.com',
                meta={'items': self.parse_items(response)},
                callback=self.yield_item
            )
            self.crawler.engine.crawl(req, spider=self)

        time.sleep(10)


def yield_item(self, response):
    for item in response.meta['items']:
        yield item

关于python - Scrapy - 在解析回调之外生成项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28699513/

相关文章:

python - 如何在 Python 中获取处理器名称?

python - boto3 : AttributeError: 'EC2' object has no attribute 'create_instances'

python - 在 Python 脚本中运行带有 "live"输出的 bash 脚本?

python - 如何使用 Python Scrapy 模块列出我网站上的所有 URL?

ssl - 握手失败: SSL Alert number 40

python - scrapy 爬虫完成后更新变量

python - 绘制树状图,根节点在顶部

python - Django:编写一个 View 来删除带有复选框的项目

python - 如果使用 XPath 是 Scrapy 中其他节点的父节点,如何从子节点获取文本

python - 分割连字符分隔单词,中间有空格 | Python