python - 我应该创建管道以使用 scrapy 保存文件吗?

标签 python scrapy web-crawler pipeline

我需要保存文件 (.pdf),但不确定如何保存。我需要保存 .pdf 文件并将它们存储在目录中,就像它们存储在我正在抓取它们的网站上一样。

据我所知,我需要制作一个管道,但据我了解,管道保存的“项目”和“项目”只是基本数据,如字符串/数字。保存文件是正确使用管道,还是我应该将文件保存在蜘蛛中?

最佳答案

是和否[1]。如果您获取 pdf,它将存储在内存中,但如果 pdf 不够大,无法填满您的可用内存,那么也可以。

您可以将 pdf 保存在蜘蛛回调中:

def parse_listing(self, response):
    # ... extract pdf urls
    for url in pdf_urls:
        yield Request(url, callback=self.save_pdf)

def save_pdf(self, response):
    path = self.get_path(response.url)
    with open(path, "wb") as f:
        f.write(response.body)

如果您选择在管道中进行:

# in the spider
def parse_pdf(self, response):
    i = MyItem()
    i['body'] = response.body
    i['url'] = response.url
    # you can add more metadata to the item
    return i

# in your pipeline
def process_item(self, item, spider):
    path = self.get_path(item['url'])
    with open(path, "wb") as f:
        f.write(item['body'])
    # remove body and add path as reference
    del item['body']
    item['path'] = path
    # let item be processed by other pipelines. ie. db store
    return item

[1] 另一种方法可能是只存储 pdf 的 url 并使用另一个进程来获取文档而不缓冲到内存中。 (例如 wget)

关于python - 我应该创建管道以使用 scrapy 保存文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7123387/

相关文章:

python - 错误 : parameters are of unsupported type By scrapy sql insert

python - XPath:通过当前节点属性选择当前和下一个节点的文本

php - 如何只加载 html(并跳过媒体文件)

c# - 从网页中提取数据,针对特定部分进行解析并显示

python - 尝试在 h5py : ValueError: Unable to set extend dataset (Dimension cannot exceed the existing maximal size 中扩展现有数据集时出错

python - 使用Remove()或Clear()后wxPython TextCtrl不聚焦

scrapy - 不抓取数据库中保存的网址

javascript - 检查获取的 URL 中是否存在元素

python - 'str' 对象没有属性 'get' - 如何告诉 python 返回的字符串是字典?

python - import _tkinter # 如果失败,你的 Python 可能没有为 Tk 配置