我在Windows Vista 64位上使用Python.org版本2.7 64位。我已经汇总了一些代码,这些代码是使用Guardian支持团队提供的API密钥的身份验证方法和由其网站的Content API代码生成器生成的一些Javascript的组合:
import requests
def get_content():
api_url = 'http://content.guardianapis.com/#/search?q=football'
payload = {
'api-key': '',
'page-size': 10,
'show-editors-picks': 'true',
'show-elements': 'image',
'show-fields': 'all'
}
response = requests.get(api_url, params=payload)
data = response.json() # convert json to python-readable format
return data
print data
{
"response": {
"status": "ok",
"userTier": "free",
"total": 1,
"results": [
{
"id": "football",
"webTitle": "Football",
"webUrl": "http://www.theguardian.com/football",
"apiUrl": "http://content.guardianapis.com/football",
"editions": [
{
"id": "football",
"webTitle": "Football",
"webUrl": "http://www.theguardian.com/football",
"apiUrl": "http://content.guardianapis.com/football",
"code": "default"
}
]
}
]
}
}
我对Python很新,并且不太了解Javascript。我认为这段代码会将结果从他们网站的足球部分打印到Python IDLE。它运行没有错误,但它不产生输出。
有人可以告诉我我做错了什么和/或我是否完全误解了这段代码的意图?
由于
答案 0 :(得分:2)
您必须调用该函数才能获得输出:
get_content() # you need to call the function
import requests
def get_content():
api_url = 'http://content.guardianapis.com/#/search?q=football'
payload = {
'api-key': 'xxxxxxxxxxx',
'page-size': 10,
'show-editors-picks': 'true',
'show-elements': 'image',
'show-fields': 'all'
}
response = requests.get(api_url, params=payload)
data = response.json() # convert json to python-readable format
print data # put print first
return data
get_content() # call function
同时拥有return data before print data
表示print data
无法访问,因为当您return data
时,您的功能结束。