用Scrapy抓取JSON响应

2024-05-10 17:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用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。


Tags: webjsonstreetnumbercityageaddresstype
2条回答

JSON不加载的可能原因是它在前后都有单引号。试试这个:

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

这与对html响应使用Scrapy的HtmlXPathSelector相同。唯一的区别是您应该使用json模块来分析响应:

class MySpider(BaseSpider):
    ...


    def parse(self, response):
         jsonresponse = json.loads(response.body_as_unicode())

         item = MyItem()
         item["firstName"] = jsonresponse["firstName"]             

         return item

希望能有所帮助。

相关问题 更多 >