Nonetype对象没有属性'\u getitem''

2024-09-26 22:51:33 发布

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

我正在尝试使用从网络下载的API包装器从新的azure Bing API获取结果。我试图按照说明实现它,但得到运行时错误:

Traceback (most recent call last):
  File "bingwrapper.py", line 4, in <module>
    bingsearch.request("affirmative action")
  File "/usr/local/lib/python2.7/dist-packages/bingsearch-0.1-py2.7.egg/bingsearch.py", line 8, in request
    return r.json['d']['results']
TypeError: 'NoneType' object has no attribute '__getitem__'

这是包装代码:

import requests

URL = 'https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/Web?Query=%(query)s&$top=50&$format=json'
API_KEY = 'SECRET_API_KEY'

def request(query, **params):
    r = requests.get(URL % {'query': query}, auth=('', API_KEY))
    return r.json['d']['results']

说明如下:

>>> import bingsearch
>>> bingsearch.API_KEY='Your-Api-Key-Here'
>>> r = bingsearch.request("Python Software Foundation")
>>> r.status_code
200
>>> r[0]['Description']
u'Python Software Foundation Home Page. The mission of the Python Software Foundation is to promote, protect, and advance the Python programming language, and to ...'
>>> r[0]['Url']
u'http://www.python.org/psf/

这是我使用包装器的代码(按照说明):

import bingsearch
bingsearch.API_KEY='abcdefghijklmnopqrstuv'
r = bingsearch.request("affirmative+action")

Tags: keyinpyimportapijsonrequestline
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:33

我自己测试过了,似乎您缺少的是正确的url编码您的查询。没有它,我得到了400码。

import urllib2
import requests

# note the single quotes surrounding the query 
URL = "https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/Web?Query='%(query)s'&$top=50&$format=json"

query = 'affirmative+action'

# query == 'affirmative%2Baction'
r = requests.get(URL % {'query': urllib2.quote(query)}, auth=('', API_KEY))
print r.json['d']['results']

您的示例没有多大意义,因为您的request包装器返回结果的list,但是在您的主要用法示例中,您调用它,然后检查返回值(即列表)上的status_code属性。该属性将出现在响应对象上,但您不会从包装器返回它。

相关问题 更多 >

    热门问题