scrapy 如何在scarpy中处理json输出

zkure5ic  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(153)

我正在写一些零碎的代码,当我想用这个命令在json中得到输出时:scrapy crawl mobileir -o myjayson.json -s FEED_EXPORT_ENCODING=utf-8我在一个单行中得到json文件,但我想在json格式中得到.我该怎么做?

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = [
                'https://www.ijpsat.com/'
    ]

    def parse(self, response):
        yield {
            'test1':response.css('#home a::text').get(),
            'test2':response.css('#about a::text').get(),
            'test3':response.css('#search a::text').get()
        }

我输出是:

[
{"test1": "Home", "test2": "About", "test3": "Search"}
]
64jmpszr

64jmpszr1#

漂亮的JSON打印

使用json.dumps()

import json

d = {
    'test1': 'Home',
    'test2': 'About',
    'test3': 'Search'
}
print(f"Before: {d}")

formatted_d = json.dumps(d, indent=2)
print(f"After: {formatted_d}")

输出量

Before: {'test1': 'Home', 'test2': 'About', 'test3': 'Search'}
After: {
  "test1": "Home",
  "test2": "About",
  "test3": "Search"
}
mm9b1k5b

mm9b1k5b2#

您可以通过添加-s FEED_EXPORT_INDENT=<number_of_spaces>来完成此操作。因此,当您执行类似于scrapy crawl quote -o items.json -s FEED_EXPORT_INDENT=2的操作时,您将得到:

[
{
  "test1": "Home",
  "test2": "About",
  "test3": "Search"
}
]

相关问题