2014-07-14 135 views
0

我正在学习如何访问Twitter的API,但得到的错误“urllib2.HTTPError:HTTP错误400:错误的请求”当我运行下面的简单代码:的Python - urllib2.HTTPError 400错误的请求

import urllib2 
import simplejson 

url = "https://api.twitter.com/1.1/search/tweets.json?screen_name=twitterapi" 

if __name__ == "__main__": 
    req = urllib2.Request(url) 
    opener = urllib2.build_opener() 
    f = opener.open(req) 
    json = simplejson.load(f) 

    for item in json: 
     print item.get("created_at") # this will get the section that is "Created At from JSON" 
     print item.get('text')  # this will get the text (in Twitter, a Tweet) 

我不确定为什么 - 我已谷歌搜索,似乎无法找到为什么这是返回错误的请求错误。谢谢你的帮助!

+1

使用要求,我得到' “坏的认证数据”'这也是我所看到的,当我使用的链接。我认为你需要一个API密钥。 –

+0

我认为是一样的,但似乎无法找到所需的API密钥文件 - 环顾[这里](https://dev.twitter.com/docs/using-search)它没有提到API密钥。 我发现[this](http://stackoverflow.com/questions/12544018/twitter-v1-1-400-bad-request)SO线程,看着Surpriya K的回应,也许你会这样做?或者,如果你正在做其他事情(oAuth和tweepy?我不确定消费者和访问令牌/密钥是什么)。 – user3718365

+0

https://apps.twitter.com/app/new这是你创建一个应用程序并获取api密钥等的地方。我不使用api,但我确定有必要有一个密钥。 –

回答

0

你需要一个API密钥,从docs

"Please note that now API v1.1 requires that the request must be authenticated, check Authentication & Authorization "

快速测试使用curl:

$curl https://api.twitter.com/1.1/search/tweets.json?q=%40twitterapi 
{"errors":[{"message":"Bad Authentication data","code":215}]} 

所以,首先,你应该得到API Key。下面是一些aditional的帮助:

+0

谢谢 - 我创建了一个API密钥...但我该从哪里去?我相信答案就在于这种情况,但我又是新的,并且不知道该把这些信息放在哪里。 – user3718365

+0

要使用这个或任何其他API,您应该发送命令。在Python中,您可以使用urllib2或使用任何第三方库作为请求:https://gist.github.com/kennethreitz/973705或者也许是专门的Twitter库:https://dev.twitter.com/docs/ Twitter的库 –