Python - urllib2.HTTPError 400 错误请求

0 投票
1 回答
588 浏览
提问于 2025-04-18 13:20

我正在学习如何访问Twitter的API,但在运行下面这段简单代码时,出现了“urllib2.HTTPError: HTTP Error 400: Bad Request”的错误:

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 个回答

0

你需要一个API密钥,具体可以参考这个文档

“请注意,现在的API v1.1要求请求必须经过认证,请查看认证与授权的相关内容。”

这里有个使用curl的快速测试:

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

所以,首先你应该去获取一个API密钥。以下是一些额外的帮助信息:

撰写回答