【问题标题】:Unable to convert unicode into json in scrapy无法在scrapy中将unicode转换为json
【发布时间】:2017-04-18 06:45:02
【问题描述】:
import scrapy
import json
class GettingtonDSpider(scrapy.Spider):
    name = "gettington_d"
    allowed_domains = ["gettington.com"]
    start_urls = ['https://api.gettington.com/v1/products?showMPP=false&rows=24&q=Keyword:south%20shore%20furniture&productfilter=null&callback=searchCallback']
    def parse(self, response):
    jsonresp = json.dumps(response.body)
    jsonresp= json.loads(jsonresp)

我尝试了很多方法,但都失败了:

  • response.text
  • 编码('utf-8')
  • response_body_as_unicode

以上都不起作用。错误如何解决?

【问题讨论】:

  • 您是否遇到任何错误?有什么具体问题吗? “以上都不起作用。”不是很有帮助。
  • 是的,我得到了 [json object could not be decoded]。
  • print(response.body) 的输出是什么?
  • url 带有浏览器元数据的产品信息,例如 searchCallback({metadata:{},products : {})
  • 这不是 json 可序列化的。

标签: python-2.7 web-scraping scrapy screen-scraping scrapy-spider


【解决方案1】:

您必须首先从response.body 中删除不必要的信息,这不是 JSON 可序列化的:

import re

    ...
    json_string = re.search(r'searchCallback\((.*)\)', response.body).group(1);
    jsonresp = json.loads(json_string)

现在您在jsonresp 中有一个dict

【讨论】:

  • 您也可以获取https://api.gettington.com/v1/products?showMPP=false&rows=24&q=Keyword:south%20shore%20furniture&productfilter=null&format=json(即删除&callback=searchCallback,并要求JSON格式)
猜你喜欢
  • 1970-01-01
  • 2016-05-05
  • 2016-08-24
  • 2016-08-25
  • 1970-01-01
  • 2018-11-19
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多