2013-05-08 69 views
2

您好我想从纽约时报API“标题”后能得到的所有信息,这里是我的代码纽约时报API,蟒蛇

from urllib2 import urlopen 
from json import loads 
import codecs 
import time 

def call_the_articles(): 
    url = "http://api.nytimes.com/svc/search/v1/article?query=US&facets=POLITICS&api-key=##" 
    return loads(urlopen(url).read()) 

articles = call_the_articles() 

if __name__ == '__main__': 


    for story in articles("results"): 
     print story['title'].encode('ascii', 'replace') 

但是当我在终端运行,则错误出来,如:

File "NYtimes.py", line 10, in <module> 
    articles = call_the_articles() 
    File "NYtimes.py", line 8, in call_the_articles 
    return loads(urlopen(url).read()) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen 
    return _opener.open(url, data, timeout) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 406, in open 
    response = meth(req, response) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 519, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 444, in error 
    return self._call_chain(*args) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 378, in _call_chain 
    result = func(*args) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 527, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 400: Bad Request 

如何解决问题?

+1

在你的url中,你制作了api键'##'而不是一些字符串。也许这可能是问题所在? – Michael0x2a 2013-05-08 01:43:21

回答

1

我怀疑你想要的是:

url = "http://api.nytimes.com/svc/search/v1/article?format=json&query=US+des_facet%3A%5BPOLITICS+AND+GOVERNMENT%5D&api-key=## 

有一个能上造成不好的请求,两件事情:

1)您使用的是facets关键字不正确。从Times API developer docs on facets

方面可以被认为是搜索“视角”。通过方面,您可以从不同的角度查看搜索结果,并且可以从不同的角度处理搜索查询。每个方面都可以被视为代表Times文章数据的属性或特征。

方面可以揭示并不直观明显的共同点和区别点。例如,标题中包含“自行车”一词的两篇文章可能会有两个截然不同的nytd_section_facet(NYTimes.com部分)值:“电影”和“健康”。同样,讨论看似不相同的话题的两篇文章,例如云计算和汽车展示,可能会共享一个des_facet(描述性主题术语)值:“新模型,设计和产品”。

2.)当你通过urlopen()发送它时,你需要URLEncode你的查询。

此外,articles将是一个字典,所以你要获得物品从使用[]

for story in articles["results"]: 

如果此处查询是不是你想要什么,纽约时报有一个工具,它允许你玩构建您的查询:NYT API Request Tool

+0

非常感谢你!问题解决了!!! – Douuga 2013-05-08 13:26:42