我是新手到Python,最近我尝试使用Scrapy刮具有多页的网站,下面是我的“spider.py”如何使用Scrapy获得结构化的JSON输出?
def parse(self, response):
sel = Selector(response)
tuples = sel.xpath('//*[td[@class = "caption"]]')
items = []
for tuple in tuples:
item = DataTuple()
keyTemp = tuple.xpath('td[1]').extract()[0]
key = html2text.html2text(keyTemp).rstrip()
valueTemp = tuple.xpath('td[2]').extract()[0]
value = html2text.html2text(valueTemp).rstrip()
item[key] = value
items.append(item)
return items
代码段通过与命令运行的代码:
scrapy crawl dumbSpider -o items.json -t json
它会发出:
{"a":"a-Value"},
{"b":"b-Value"},
{"c":"c-Value"},
{"a":"another-a-Value"},
{"b":"another-b-Value"},
{"c":"another-c-Value"}
但其实我是想是这样的:
{"a":"a-Value", "b":"b-Value", "c":"c-Value"},
{"a":"another-a-Value", "b":"another-b-Value", "c":"another-c-Value"}
我尝试了一些方法来调整spider.py例如使用临时列表来存储单个网页的所有“项目”,然后将临时列表附加到“项目”,但不知何故它不起作用。
已更新:缩进是固定的。
考虑建立在个案第一个将充满你的分字典新的两个字典,直到它会发现,特别是关键的,比如'了'已经存在。如果发生这种情况 - 创建新的字典并执行相同的操作。 – PatNowak
@PatNowak感谢您的评论!但是该网站上显示的数据过于灵活而无法监控。我实际上无法知道我什么时候会在特定页面中接近尾声。 – mightyheptagon
它总是为了?我的意思是它总是以3为单位,你想要第一个3,然后是其他3等等? – eLRuLL