首页 > 解决方案 > Scrapy Splash 屏幕截图管道不起作用

问题描述

我正在尝试使用 Scrapy Splash 保存抓取网页的屏幕截图。我已将此处找到的代码复制并粘贴到我的管道文件夹中:https ://docs.scrapy.org/en/latest/topics/item-pipeline.html

这是来自网址的代码:

import scrapy
import hashlib
from urllib.parse import quote


class ScreenshotPipeline(object):
    """Pipeline that uses Splash to render screenshot of
    every Scrapy item."""

    SPLASH_URL = "http://localhost:8050/render.png?url={}"

    async def process_item(self, item, spider):
        encoded_item_url = quote(item["url"])
        screenshot_url = self.SPLASH_URL.format(encoded_item_url)
        request = scrapy.Request(screenshot_url)
        response = await spider.crawler.engine.download(request, spider)

        if response.status != 200:
            # Error happened, return item.
            return item

        # Save screenshot to file, filename will be hash of url.
        url = item["url"]
        url_hash = hashlib.md5(url.encode("utf8")).hexdigest()
        filename = "{}.png".format(url_hash)
        with open(filename, "wb") as f:
            f.write(response.body)

        # Store filename in item.
        item["screenshot_filename"] = filename
        return item

我还按照此处找到的设置启动说明进行了操作:https ://github.com/scrapy-plugins/scrapy-splash

当我调用该命令scrapy crawl spider时,除管道外,一切正常。这是我看到的“错误”。

<coroutine object ScreenshotPipeline.process_item at 0x7f29a9c7c8c0>

蜘蛛正确地产生了该项目,但它不会处理该项目。

有人有建议吗?谢谢你。

编辑:

我认为发生的事情是 Scrapy 像往常一样调用 process_item() 方法。但是根据这些文档:https ://docs.python.org/3/library/asyncio-task.html 必须以不同的方式调用协程对象。

asyncio.run(process_item()) 而不是 process_item()。我想我可能需要修改源代码?

标签: pythonscrapyscrapy-splash

解决方案


您应该在蜘蛛内的脚本中使用scrapy-splash,而不是在管道中。

我遵循了这个文档,它对我有用。


推荐阅读