Skip to main content
 首页 » 编程设计

python之在 scrapy 中抓取 json 响应

2025年05月04日9lovecherry

我一直在学习用 scrapy 抓取页面。一些呈现给我的数据是 JSON 格式的,到目前为止我还无法成功地抓取 JSON 页面。我知道这是可以做到的(感谢我之前唯一的问题和有用的回复),但我就是做不到。我想知道是否 a) 有人知道一个成功的 JSON scrapy 脚本示例,或者 b) 我可以请您提供一些指示。

我一直在使用此页面寻求帮助: http://www.jroller.com/evans/entry/parsing_json_with_python , 试图抓取用作示例的页面。

我的 spider 跑了,但没有抓到任何东西。我知道我犯了错误,但我觉得我至少改变了 spyder 的每一个小方面,现在却让自己感到困惑。

我的蜘蛛的基础(根据以下建议编辑)是这样的:

from scrapy.spider import BaseSpider 
from scrapy.selector import HtmlXPathSelector 
from learnjson.items import learnjsonitems, Field 
import json 
import urllib2 
 
class MySpider(BaseSpider): 
name = "jsonexample" 
allowed_domains = ["googleapis.com"] 
req = urllib2.urlopen('http://maps.googleapis.com/maps/api/geocode/json?address=8-10%20Broadway,%20London%20SW1H%200BG,%20United%20Kingdom&sensor=false' 
) 
 
def json_parse(self, response): 
    jsonresponse = json.loads(response.body_as_unicode()) 
    latitude = jsonresponse["lat"] 
 
 
    print item["lat"] 

以被抓取的页面为例(不是我的数据,只是用来练习的东西),我一直在尝试提取街道地址和纬度/经度,但我尝试过的任何方法似乎都不起作用。

请您参考如下方法:

我想你错过了导入 json.Add

在您的代码中导入 json。

同时使用 urllib2 解压缩并打开您的 json 文件。它会正常工作。 您可以为 json 响应附加一个代码,例如。

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

希望这有帮助:)