-5
import requests
URL = "https://mykey:mykey@api.datamarket.azure.com/Bing/Search/Web?$format=json&Query=%(query)s"
API_KEY = 'mykey'
def request(query, **params):
    query = ('%27'+query+ '%27')
    r = requests.get(URL % {'query': query}, auth=('', API_KEY))
    print r.content
    #return r.json()['d']['results']    
r = request("JasonBourne")
print r[0]['Url']

它会产生我上面提到的错误

print r[0]['Url']

r.content 的值为

{"d":{"results":[{"__metadata":{"uri":"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=\u0027JasonBourne\u0027&$skip=0&$top=1","type":"WebResult"},"ID":"caac4e4d-b701-497a-ae61-f2b2993685d5","Title":"Jason Bourne - Wikipedia, the free encyclopedia","Description":"Jason Charles Bourne is a fictional character and the protagonist of a series of novels by Robert Ludlum and subsequent film adaptations. He first appeared in the ...","DisplayUrl":"en.wikipedia.org/wiki/Jason_Bourne","Url":"http://en.wikipedia.org/wiki/Jason_Bourne"},{"__metadata":{"uri":"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=\u0027JasonBourne\u0027&$skip=1&$top=1","type":"WebResult"},"ID":"32688769-2490-470e-9903-8ea6b836ff97","Title":"JasonBourne.com","Description":"Welcome to Loscocco Media ... Created by author Robert Ludlum and brought to the silver screen with the face of Matt Damon, Jason Bourne is an enigmatic killer in ...","DisplayUrl":"jasonbourne.com","Url":"http://jasonbourne.com/"},{"__metadata":{"uri":"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=\u0027JasonBourne\u0027&$skip=2&$top=1","type":"WebResult"},"ID":"5db32b8f-2940-4542-a2e7-379e347201c3","Title":"Jason Bourne | The Bourne Identity | The Bourne Ultimatum | The ...","Description":"Jason Bourne is a CIA assassin & the hero of a trilogy of movies based on the books of Robert Ludlam; these are The Bourne Identity, Bourne Ultimatum, & Bourne Supremacy.","DisplayUrl":"jason-bourne.com","Url":"http://jason-bourne.com/"},{"__metadata":}

这不是全部价值,因为它太大了。

4

1 回答 1

2

您的函数不返回任何内容。打印与返回值不同。

函数的默认返回值为None,这会导致您的错误。您想返回一些东西,很可能是r.json()

def request(query, **params):
    query = ('%27'+query+ '%27')
    r = requests.get(URL % {'query': query}, auth=('', API_KEY))
    return r.json()

然后循环结果:

r = request("JasonBourne")
for res in r['d']['results']:
    print res['Url']

或使用列表理解将它们全部收集在列表中:

r = request("JasonBourne")
urls = [res['Url'] for res in r['d']['results']]

给你一个清单urls

于 2013-08-12T10:54:43.093 回答