2014-07-14 134 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的庫 –