前提・実現したいこと
scrapyで起点となるurlから取得したテキストをparseした得られた画像urlを元に画像をダウンロードする処理をする。
このとき、画像ファイル名の付け方で悩んでいる。
ImageItemクラスで定義して、callbackを利用すればよいのか、何もcallbackせずに、self.parseメソッド上に画像のダウンロード処理を入れて、
普通にファイル名を生成するべきなのか。
該当のソースコード
import scrapy,hashlib,json class ExampleSpider(scrapy.Spider): name = 'example-spider' allowed_domains = ['example.com'] start_urls = ['https://example.com/specify_url'] def start_requests(self): urls = self.start_urls for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): info_data = response.(なんらかのparse処理) info_data = json.loads(info_data) yield { "title" : info_data["title"] } image_url = info_data["image_url"] image_blob = scrapy.Request(url=image_url ) ## もしくは image_blob = (self.get_imageを呼び出す何らかの画像取得処理) image_hash = hashlib.sha512(image_blob).hexdigest() image_filename = info_data["title"]+"-"+image_hash+"-"+image_url.name yield{ image_url:image_url ,image_blobdata : image_blob , image_hash : image_hash , image_filename : image_filename } def get_image(self, response): image_url = info_data["image_url"] image_blob = scrapy.Request(url=image_url ) image_hash = hashlib.sha512(image_blob).hexdigest() image_filename = info_data["title"]+"-"+image_hash+"-"+image_url.name yield{ image_url:image_url ,image_blobdata : image_blob , image_hash : image_hash , image_filename : image_filename }
特定のurlから複数の画像urlが取得可能であり、画像特有の処理があるため、
画像には特別に別のクラスを導入するべきかと思います。
しかし、callback先にImageItemクラスを生成して、
画像特有の処理をする際に、画像ファイル名に、callback元の変数値(例えばtitle)を利用するので、どのような処理をすればよいかわかりません。
ただし、画像特有の処理と言っても、
ある1つの特定urlに対して、複数の画像が存在しても、
それらは異なるタグ(image_url,image_big_url)のようなもので、
最終的な保存のときの、Itemクラスでのkey名は、
・image_url
・image_hash
・image_blob
・image_filename
・image_big_url
・image_big_hash
・image_big_blob
・image_big_filename
のような区別を行うため、
callback先でyieldによる保存を行うにしても、このようなkey名の変更に対応できるようなcallback関数の呼び出し方が必要です。
となると、素直にcallbackせずに、self.parse内に希望の画像特有の処理を入れるべきかなと悩んでます。
##最終的な処理
https://example.com/specify_urlから特定テキストをparse処理し、
json形式(というよりdict形式)にして、info_dataに格納します。
info_dataは、title,(何かのidなど),image_url,image_big_urlです。
これを画像特有の処理を行い、最終的には以下のkeyを持つitemクラスのインスタンスを生成します。
・特定テキストの取得時刻
・title
・(何かのidなど)
・image_url
・image_hash
・image_blob
・image_filename
・image_big_url
・image_big_hash
・image_big_blob
・image_big_filename
そして、csvかdbに保存するつもりです。
補足情報(FW/ツールのバージョンなど)
python 3.6.4
scrapy 1.5.1

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。