将Scrapy Python输出写入JSON文件

将Scrapy Python输出写入JSON文件,python,json,web-scraping,scrapy,append,Python,Json,Web Scraping,Scrapy,Append,我不熟悉Python和web抓取。在这个程序中,我想将所有3个链接的最终输出产品名称和价格写入JSON文件。请帮忙 import scrapy from time import sleep import csv, os, json import random class spider1(scrapy.Spider): name = "spider1" def start_requests(self):

我不熟悉Python和web抓取。在这个程序中,我想将所有3个链接的最终输出产品名称和价格写入JSON文件。请帮忙

    import scrapy
    from time import sleep
    import csv, os, json
    import random


    class spider1(scrapy.Spider):
        name = "spider1"

        def start_requests(self):
            list = [
                "https://www. example.com/item1",
                "https://www. example.com/item2",
                "https://www. example.com/item3"]

            for i in list:
                yield scrapy.Request(i, callback=self.parse)
                sleep(random.randint(0, 5))

        def parse(self, response):
            product_name = response.css('#pd-h1-cartridge::text')[0].extract()
            product_price = response.css(
                '.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
                '::text')[3].extract()

            name = str(product_name).strip()
            price = str(product_price).replace('\n', "")

data = {name, price}

yield data

extracted_data = []
    while i < len(data):

        extracted_data.append()
        sleep(5)
    f = open('data.json', 'w')
    json.dump(extracted_data, f, indent=4)
您没有关闭data.json文件,因此它处于缓冲状态,不会被写入

添加一个关闭方法:

或者使用with语句自动关闭文件:

with open('data.json', 'w') as f:
    json.dump(extracted_data, f, indent=4)
确保每次使用“w”标志时确实要覆盖该文件。如果没有,请使用“a”append标志。

您没有关闭data.json文件,因此它处于缓冲状态,不会被写入

添加一个关闭方法:

或者使用with语句自动关闭文件:

with open('data.json', 'w') as f:
    json.dump(extracted_data, f, indent=4)

确保每次使用“w”标志时确实要覆盖该文件。如果没有,请使用“a”append标志。

您不需要创建文件,scrapy可以做到这一点,当您在最后一次解析中返回项目时,首先创建一个ItemLoader和项目,如果您需要json格式的数据,可以在爬行爬行器时添加一个参数-o

例如:

scrapy crawl <spidername> -o <filename>.json

你不需要创建一个文件,scrapy可以做到,首先创建一个ItemLoader和Item,当你在最后一次解析中返回Item时,如果你需要json格式的数据,你可以在爬行时添加一个参数-o

例如:

scrapy crawl <spidername> -o <filename>.json

实际上有一个scrapy命令来执行此操作:

但由于您要求提供python代码,我提出了以下建议:

    def parse(self, response):
        with open("data_file.json", "w") as filee:
            filee.write('[')
            for index, quote in enumerate(response.css('div.quote')):
                json.dump({
                    'text': quote.css('span.text::text').extract_first(),
                    'author': quote.css('.author::text').get(),
                    'tags': quote.css('.tag::text').getall()
                }, filee) 
                if index < len(response.css('div.quote')) - 1:
                    filee.write(',')
            filee.write(']')

它的作用与json文件的scrapy输出命令相同。

实际上有一个scrapy命令来执行此操作:

但由于您要求提供python代码,我提出了以下建议:

    def parse(self, response):
        with open("data_file.json", "w") as filee:
            filee.write('[')
            for index, quote in enumerate(response.css('div.quote')):
                json.dump({
                    'text': quote.css('span.text::text').extract_first(),
                    'author': quote.css('.author::text').get(),
                    'tags': quote.css('.tag::text').getall()
                }, filee) 
                if index < len(response.css('div.quote')) - 1:
                    filee.write(',')
            filee.write(']')

它的作用与json文件的scrapy输出命令相同。

Thanx。但是JSON输出只显示最后一个链接的名称和价格。我想将所有3个链接中的名称和价格添加到提取的_数据中,然后将其转储到json文件中。但是JSON输出只显示最后一个链接的名称和价格。我想将所有3个链接中的名称和价格添加到提取的_数据中,然后将其转储到json文件中。“a”append标志就是您的朋友。谢谢。它起作用了;参考链接非常有用。谢谢。它起作用了;参考链接非常有用。