我有一个进程(在Scrapy外部),它生成到pdf文档的URL列表,以及我想保存每个pdf的列表文件。
以下是解释了如何将URL列表作为命令行参数传递给Scrapy,但是,有没有办法传递文件并确保每个pdf都保存在提供的文件中?
我怀疑我需要基于文档中提供的本教程修改下面的内容,但据我了解,parse
方法用于确定如何处理一个响应,而不处理一个列表。
def parse(self, response):
filename = response.url.split("/")[-2] + '.html'
with open(filename, 'wb') as f:
f.write(response.body)
有什么建议吗?
发布于 2016-01-28 23:13:06
原来这是一个与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)
发布于 2016-01-26 13:14:18
如果我是对的,您不能用刮伤“抓取”一个pdf,但是如果您想保存pdfs,就不需要爬行它,只需要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")
https://stackoverflow.com/questions/34985737
复制相似问题