追加する代わりに上記のファイルを上書きする方法はありますか?ファイルを追加するのではなく、スキンがjsonファイルを上書きする
例)
scrapy crawl myspider -o "/path/to/json/my.json" -t json
scrapy crawl myspider -o "/path/to/json/my.json" -t json
my.jsonファイルを追加する代わりに、それを上書きします。
追加する代わりに上記のファイルを上書きする方法はありますか?ファイルを追加するのではなく、スキンがjsonファイルを上書きする
例)
scrapy crawl myspider -o "/path/to/json/my.json" -t json
scrapy crawl myspider -o "/path/to/json/my.json" -t json
my.jsonファイルを追加する代わりに、それを上書きします。
scrapy crawl myspider -t json --nolog -o - > "/path/to/json/my.json"
これは古いScrapyのwell-known "problem"です。あなたがクロールを開始し、以前の呼び出しの結果を保持したくないたびににはにファイルを削除する必要があります。この背後にあるアイデアは、異なるサイトまたは同じサイトを別の時間枠でクロールして、誤って収集した結果を失う可能性があるということです。それは悪くなる可能性があります。
'a'
の代わりに'w'
のターゲットファイルを開く場所に、独自のアイテムパイプラインを作成する方法があります。
のドキュメントで、このようなパイプラインの外観を作成する方法を参照するには、次のhttp://doc.scrapy.org/en/latest/topics/item-pipeline.html#writing-your-own-item-pipeline(特にJSONの輸出用:http://doc.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-a-json-file)
私の編集でカスタムJsonItemExporterクラスをインスタンス化するexporter.pyスクリプトと同様のことをすることはできますか? (私はまだ初心者のプログラマーなので、私はそれを正しく言っているのか分かりません)、self.file = open(ファイル、 'wb')を追加しますか?それが正しい方法かどうかわからない – hooliooo
受け入れ答えは私にunvalid JSONに問題を与えた、ので、これは仕事ができる:
find "/path/to/json/" -name "my.json" -exec rm {} \; && scrapy crawl myspider -t json -o "/path/to/json/my.json"
この問題を解決するために、myprojectディレクトリにscrapy.extensions.feedexport.FileFeedStorage
のサブクラスを作成しました。
これは私のcustomexport.py
です:
"""Custom Feed Exports extension."""
import os
from scrapy.extensions.feedexport import FileFeedStorage
class CustomFileFeedStorage(FileFeedStorage):
"""
A File Feed Storage extension that overwrites existing files.
See: https://github.com/scrapy/scrapy/blob/master/scrapy/extensions/feedexport.py#L79
"""
def open(self, spider):
"""Return the opened file."""
dirname = os.path.dirname(self.path)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
# changed from 'ab' to 'wb' to truncate file when it exists
return open(self.path, 'wb')
その後、私が(参照:https://doc.scrapy.org/en/1.2/topics/feed-exports.html#feed-storages-baseを):私のsettings.py
に以下を追加
FEED_STORAGES_BASE = {
'': 'myproject.customexport.CustomFileFeedStorage',
'file': 'myproject.customexport.CustomFileFeedStorage',
}
私が書くたびのため、それが上書きされたファイルにこの。
ありがとう!これは私が探していたものです。単純な " - >"部分はファイルを上書きしますか? – hooliooo
-o - :標準出力にリダイレクトし、>標準出力を次のパスの新しいファイルにリダイレクトします。私はそれを使用し、奇妙に働いた、私は無効なjson出力を得たように。 – miguelfg
Dockerコンテナ内でsubprocess.check_outputを使用して呼び出すと、これがなぜ機能しないのでしょうか? コマンド '[' scrapy '、' crawl '、' spider_name '、' -t '、' json '、' --nolog '、' -o '、' - '、'> '、' output.json ' 、 '-a'、 'url = url.jpg]'は0以外の終了ステータス2を返しました。 –