Scrapy выводит некорректный файл json.Когда я пытаюсь работать с указанным файлом json, с
import json
, я сталкиваюсь с этой ошибкой
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 311 column 94 (char 28466)
Это вызвано добавлением ненужной квадратной скобки в началефайл JSON.
Файл JSON будет выглядеть следующим образом
[[{"city": "New York", "state": "New York", "rank": "1\n", "population": ["8,622,698\n"]},
{"city": "Los Angeles", "state": "California", "rank": "2\n", "population": ["3,999,759\n"]}]`
Я использую эту команду для сканирования:
scrapy crawl wiki -o items.json
Когда я удаляю квадратную скобку вручную, она работает нормально.Это другой скрипт на python:
import json
with open ("items1.json", "r") as read_file:
data = json.load(read_file)
print(type(data))
edit
рассматриваемый паук
# -*- coding: utf-8 -*-`
import scrapy
class WikiSpider(scrapy.Spider):
name = "wiki"
allowed_domains = ["en.wikipedia.org"]
start_urls = ('https://en.wikipedia.org/wiki/List_of_United_States_cities_by_population')
def parse(self, response):
table = response.xpath('//table')[4]
trs = table.xpath('.//tr')[1:]
for tr in trs:
rank = tr.xpath('.//td[1]/text()').extract_first()
city = tr.xpath('.//td[2]//text()').extract_first()
state = tr.xpath('.//td[3]//text()').extract()[1]
population = tr.xpath('.//td[4]//text()').extract()
yield {
'rank':rank,
'city': city,
'state': state,
'population':population
}