【问题标题】:How can I pass a list of output file paths to Scrapy?如何将输出文件路径列表传递给 Scrapy?
【发布时间】:2016-01-25 05:32:31
【问题描述】:

我有一个进程(在 Scrapy 外部),它生成一个指向 pdf 文档的 URL 列表,以及一个我想要保存每个 pdf 的文件路径列表。

The following 解释了如何将 URL 列表作为命令行参数传递给 Scrapy,但是,有没有办法传递文件路径并确保每个 pdf 都保存在提供的文件路径中?

我怀疑我需要根据文档中提供的the tutorial 修改以下内容,但据我了解,parse 方法用于确定如何处理一个响应,而不是处理列表。

def parse(self, response):
    filename = response.url.split("/")[-2] + '.html'
    with open(filename, 'wb') as f:
        f.write(response.body)

有什么建议吗?

【问题讨论】:

  • 您是否将第一个 PDF 保存到第一个文件路径等等,或者您是否有其他方案将 RDF 链接到路径?也许您可以提供一些伪代码向我们展示您想要的逻辑。

标签: scrapy


【解决方案1】:

原来这是一个与 python 相关的问题,与 Scrapy 本身无关。以下是我所追求的解决方案。

# To run;    
# > scrapy runspider pdfGetter.py -a urlList=/path/to/file.txt -a pathList=/path/to/another/file.txt

import scrapy
class pdfGetter(scrapy.Spider):
    name = "pdfGetter"

    def __init__(self,urlList='',pathList=''):
        self.File=open(urlList)
        self.start_urls = [url.strip() for url in self.urlFile.readlines()]
        self.File.close()

        self.File=open(pathList)
        self.save_urls = [path.strip() for path in self.pathFile.readlines()]
        self.File.close()

    def parse(self, response):
        idx = self.start_urls.index(response.url)
        with open(self.save_urls[idx], 'wb') as f:
            f.write(response.body)    

【讨论】:

    【解决方案2】:

    如果我是正确的,你不能用scrapy“抓取”一个pdf,但是如果你想保存pdf,你不需要抓取它,你只需要url,例如:

    import urllib
    from scrapy import Spider
    
    class MySpider(Spider):
        name = "myspider"
        start_urls = ['http://website-that-contains-pdf-urls']
    
        def parse(self, response):
            urls = response.xpath('//xpath/to/url/@href').extract()
            for url in urls:
                urllib.urlretrieve(url, filename="name-of-my-file.pdf")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      相关资源
      最近更新 更多