python - 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()。我想我可能需要修改源代码?
解决方案
您应该在蜘蛛内的脚本中使用scrapy-splash,而不是在管道中。
我遵循了这个文档,它对我有用。
推荐阅读
- java - 未在 servlet 中获得连接,但在普通 java 类中获得连接
- powerquery - Power Query - 有条件地替换/清除多列中的整个单元格
- php - 从 foreach 生成的下拉列表中获取选定的答案
- codeigniter-4 - 我在 CI 4 CodeIgniter DebugBar 中遇到错误:找不到文件“WRITEPATH/debugbar/debugbar_1623158273”
- javascript - 无法在本机反应中从数据对象中提取项目
- java - Intellij IDEA Contract 误报语法错误
- node.js - 如何在mongodb中使用主集合的objectID在另一个集合中查找
- sql - 在 where 条件下使用 MAX 函数获取时间
- operators - Solidity ++ 运算符未按预期分配
- elasticsearch - ElasticSearch/ElasticCloud 警报创建