我只是Python和Scrapy的新手,所以请耐心等待。我在我的网站上使用Tipuesearch,我需要以某种.json格式从Scrapy中提取数据,以使搜索工作正常。 json文件应如下所示:
{"pages": [
{"title": "x", "text": "x", "tags": "x", "url": "x"},
{"title": "x", "text": "x", "tags": "x", "url": "x"},
{"title": "x", "text": "x", "tags": "x", "url": "x"}
]}
但是经过几个小时的不同测试后,我才得到这种格式:
[
{"pages": {"title": "x", "text": "x", "tags": x", "url": "x"}},
{"pages": {"title": "x", "text": "x", "tags": x", "url": "x"}},
{"pages": {"title": "x", "text": "x", "tags": x", "url": "x"}}
]
Tipuesearch无法识别此格式,并且无法阻止整个搜索功能的运行。我怎样才能将.json文件转换为我先提到的确切格式?我带着我的蜘蛛
scrapy runspider techbbs.py -o test.json -t json
命令,我不使用任何管道或项目导出器。
我的spider.py看起来像这样
# -*- coding: utf-8 -*-
import scrapy
from urllib.parse import urljoin
from scrapy.selector import Selector
class TechbbsItem(scrapy.Item):
pages = scrapy.Field()
title = scrapy.Field()
text= scrapy.Field()
tags= scrapy.Field()
url = scrapy.Field()
class TechbbsSpider(scrapy.Spider):
name = 'techbbs'
allowed_domains = ['bbs.io-tech.fi']
start_urls = ['https://bbs.io-tech.fi/forums/prosessorit-emolevyt-ja-muistit.73/?prefix_id=1'
]
def parse(self, response):
links = response.css('a.PreviewTooltip::attr(href)').extract()
for l in links:
url = response.urljoin(l)
yield scrapy.Request(url, callback=self.parse_product)
def parse_product(self, response):
product_title = response.xpath('normalize-space(//h1/span/following-sibling::text())').extract()
product_text = response.xpath('//b[contains(.,"Hinta:")]/following-sibling::text()[1]').re('([0-9]+)')
product_tags = response.xpath('//a/span[@itemprop]').extract()
product_url = response.xpath('//html/head/link[7]/@href').extract()
items = []
for title, text, tags, url in zip(product_title, product_text, product_tags, product_url):
item = TechbbsItem()
item['pages'] = {}
item['pages']['title'] = title
item['pages']['text'] = text
item['pages']['tags'] = tags
item['pages']['url'] = url
items.append(item)
return items
答案 0 :(得分:0)
我会通过编写自定义项目导出器来完成此操作:
start_exporting()
和finish_exporting()
方法以获得所需的输出(如果您遇到问题,请查看the source)