首页 文章

使用Scrapy刮擦JSON响应

提问于
浏览
29

如何使用Scrapy来抓取返回JSON的Web请求?例如,JSON看起来像这样:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

我希望抓取特定项目(例如上面的 namefax )并保存到csv .

2 回答

  • 0

    它是's the same as using Scrapy' s HtmlXPathSelector 用于HTML响应 . 唯一的区别是你应该使用 json 模块来解析响应:

    class MySpider(BaseSpider):
        ...
    
    
        def parse(self, response):
             jsonresponse = json.loads(response.body_as_unicode())
    
             item = MyItem()
             item["firstName"] = jsonresponse["firstName"]             
    
             return item
    

    希望有所帮助 .

  • 44

    JSON未加载的可能原因是它之前和之后都有单引号 . 试试这个:

    json.loads(response.body_as_unicode().replace("'", '"'))
    

相关问题