【问题标题】:Extract Json data from RestFul webservice using Python使用 Python 从 RestFul Web 服务中提取 Json 数据
【发布时间】:2015-04-22 18:02:10
【问题描述】:

我们使用 Bugsplatsoftware.com 收集所有崩溃。他们有一个返回 JSON 数据的RESTFull web 服务。我想获取individual crashes 的数据。数据在登录名/密码后面...

我尝试了以下方法,但结果不如预期。

import requests
from requests.auth import HTTPBasicAuth

args={'id':11111,'data':0}

response=requests.get("https://www.bugsplatsoftware.com/individualCrash",params=args,auth=HTTPBasicAuth("username","password"))

data=response.json()

response.headers 返回关注

response.headers
{'content-length': '10549', 'connection': 'close', 'server': 'Apache/2.4.12 (Win32) OpenSSL/1.0.1l PHP/5.5.21', 'x-frame-options': 'SAMEORIGIN', 'x-pingback': 'https://www.bugsplatsoftware.com/xmlrpc.php', 'expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'x-xss-protection': '1; mode=block', 'date': 'Wed, 22 Apr 2015 17:43:37 GMT', 'content-encoding': 'gzip', 'link': '<https://www.bugsplatsoftware.com/?p=363>; rel=shortlink', 'vary': 'Accept-Encoding,User-Agent', 'x-content-type-options': 'nosniff', 'x-powered-by': 'PHP/5.5.21', 'content-type': 'text/html; charset=UTF-8', 'pragma': 'no-cache'}

我需要做什么来获取 json 数据?提前致谢。

当我打印 response.url 时,它显示 https://www.bugsplatsoftware.com/login/ 而不是 https://www.bugsplatsoftware.com/individualCrash/?id=11111&data=0....

marmeladze, "bugsplatsoftware.com/individualCrash?id=11111&data=0";返回 json 数据(至少在浏览器中),这就是我需要的。

pygeek,当我调用 response.content 时,数据似乎是 html 页面.....

Ivan,如何为 requests.get 指定“内容类型”?

似乎我需要做类似Using Python Requests: Sessions, Cookies, and POST的事情我尝试了以下

import requests
s=requests.Session()
data={"login":'tester',"password":'testing'}
url="https://wwww.bugsplatsoftware.com/login"
r=s.post(url,data=data) 

我收到未经授权的错误消息

或者如果我只是这样做

s.get(url) 我收到了太多重定向

【问题讨论】:

  • 您要准确提取什么?
  • 您是否尝试过将内容类型从 text/html 更改为 text/json?
  • 你检查过响应正文了吗?

标签: python json rest python-requests


【解决方案1】:

这实际上非常简单。 JSON 在结构上接近 Python 列表和字典。因此,您需要做的就是将您从 Web 服务调用返回的 JSON 字符串转换为适当的序列类型,然后您可以对其使用列表推导来提取您想要的任何内容。

这是我创建的一些示例代码,用于调用我的一个简单的 Web 服务。

import urllib, json, collections    

def getURLasString(url):
    s = urllib.urlopen(url).read()
    return s

def convertJSONStringToSequence(source):
    j = json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(source)
    return j

def getURLasJSONSequence(url):
    s = getURLasString(url)
    return convertJSONStringToSequence(s)

url = "http://127.0.0.1:8081/lookupnames" # my local web service
s = getURLasString(url)
print s
j = getURLasJSONSequence(url)
print j

sampleJSON = [{"LastName": "DaVinci", "FirstName": "Leonardo"}, {"LastName": "Newton", "FirstName": "Isaac"}]

filteredList = [e["FirstName"] for e in sampleJSON if e["LastName"].startswith("D")]
print filteredList

其中大部分只是我为使其更容易而创建的功能,但主要部分是这个;你需要导入 json 包。然后 JSONDecoder 会将您从 Web 服务调用返回的字符串转换为本地 Python 序列之一(通常是字典列表)。我编写了一堆辅助函数来将字符串转换为序列,或者直接调用 URL 并返回序列。

我编写的程序会给出以下输出:

[{"LastName": "DaVinci", "FirstName": "Leonardo"}]
[OrderedDict([(u'LastName', u'DaVinci'), (u'FirstName', u'Leonardo')])]
['Leonardo']

【讨论】:

猜你喜欢
  • 2011-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多