CHK:
私はコマンドでscrapyを使用する場合scrapy crawl my-spider --logfile=output.log
、私は何の問題もなく項目とそのログを取得します。しかし、彼らが表示されている方法は、非常に私の目に不快されています。
私は何を得ます:
...
2020-02-26 16:23:32 [scrapy.core.scraper] DEBUG: Scraped from <200 https://some-url.com>
{'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3'}
...
私が何をしたいです:
...
2020-02-26 16:23:32 [scrapy.core.scraper] DEBUG: Scraped from <200 https://some-url.com>
{'key_1': 'value_1',
'key_2': 'value_2',
'key_3': 'value_3'}
...
どうやってやるの?
Smuuf:
あなたは、あなた自身の使用するScrapyを設定することができ、ログフォーマッタ延長する、標準フォーマッタをし、それをダンプする前にペイロードをフォーマットログにします。
例として、サンプルプロジェクトを考えてみましょうquotesbotで述べたscrapyのドキュメントを。
Scrapyドキュメントは言う、我々が使用できる設定があります:
LOG_FORMATTER
デフォルト:
scrapy.logformatter.LogFormatter
さまざまなアクションのためのログメッセージをフォーマットするために使用するクラス。
だから、中settings.py
のファイルあなたはScrapy教えてくれるの行を追加します。ログフォーマッタを使用する必要があります。
BOT_NAME = 'quotesbot'
SPIDER_MODULES = ['quotesbot.spiders']
NEWSPIDER_MODULE = 'quotesbot.spiders'
...
...
...
LOG_FORMATTER = 'quotesbot.my_pretty_formatter.MyPrettyFormatter' # Add this line.
その後で、新しい「かわいいフォーマッタ」を作成します./quotesbot/my_pretty_formatter.py
:
from pprint import pformat
from scrapy.logformatter import LogFormatter
class MyPrettyFormatter(LogFormatter):
def scraped(self, item, response, spider):
pretty_item = pformat(item) # This will prettify the item that's about to be logged.
return super().scraped(pretty_item, response, spider)
以上です。
標準の出力ログフォーマッタ:
2020-02-26 19:57:06 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/10/>
{'text': '“... a mind needs books as a sword needs a whetstone, if it is to keep its edge.”', 'author': 'George R.R. Martin', 'tags': ['books', 'mind']}
私たちの新しいの出力はかなりフォーマッタ:
2020-02-26 19:55:43 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/10/>
{'author': 'George R.R. Martin',
'tags': ['books', 'mind'],
'text': '“... a mind needs books as a sword needs a whetstone, if it is to '
'keep its edge.”'}