【发布时间】:2020-05-13 00:50:11
【问题描述】:
我是 Scrapy 的新手,并且一直在尝试解决这个问题。提前致谢。 我想获得来自不同页面的链接列表。每个 parse 方法都会生成一个带有链接列表的对象,但输出文件只是转储这些对象而不将它们放入列表中,因此它不是有效的 json。
输出是
{"links": *list of links*}
{"links": *list of links*}
但我想在列表中看到它
[{"links": *list of links*},
{"links": *list of links*}]
使用$ scrapy crawl links -o links.json 运行它
class LinksSpider(scrapy.Spider) :
name = "links"
def start_requests(self):
start_urls = [
"https://www.snerpa.is/net/isl/isl-th.htm",
"https://www.snerpa.is/net/snorri/heimskri.htm"
]
for url in start_urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response) :
linksList = []
for link in response.xpath("//a/@href"):
if link.get().index("/") < 2:
linksList.append("https://www.snerpa.is/net/isl" + link.get()[1:])
yield {
"links": linksList
}
编辑: Scrapy 2.1.0版
我发现我做错了什么。我之前复制了一个sn-p并把它放在settings.py中 改变这个
from scrapy.exporters import JsonLinesItemExporter
class MyJsonLinesItemExporter(JsonLinesItemExporter):
def __init__(self, file, **kwargs):
super(MyJsonLinesItemExporter, self).__init__(file, ensure_ascii=False, **kwargs)
FEED_EXPORTERS = {
'jsonlines': 'postscrape.settings.MyJsonLinesItemExporter',
'jl': 'postscrape.settings.MyJsonLinesItemExporter',
'json': 'postscrape.settings.MyJsonLinesItemExporter'
}
到这里……
from scrapy.exporters import JsonItemExporter
class MyJsonItemExporter(JsonItemExporter):
def __init__(self, file, **kwargs):
super(MyJsonItemExporter, self).__init__(file, ensure_ascii=False, **kwargs)
FEED_EXPORTERS = {
'jsonlines': 'postscrape.settings.MyJsonItemExporter',
'jl': 'postscrape.settings.MyJsonItemExporter',
'json': 'postscrape.settings.MyJsonItemExporter'
}
修复了问题
【问题讨论】:
-
你的scrapy版本是多少?
标签: json python-3.x web-scraping scrapy