NYtimes API,python

时间:2013-05-08 01:16:41

标签: python api

您好我希望在“标题”之后获取所有信息。来自NYtimes 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 个答案:

答案 0 :(得分: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

  

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

     

分面可以揭示并不是很明显的共性和区别点。例如,标题中带有“bicycle”一词的两篇文章可能有两个非常不同的nytd_section_facet(NYTimes.com部分)值:“Movies”和“Health”。同样,两篇讨论看似截然不同的主题的文章,如云计算和车展,可能会共享一个des_facet(描述性主题词)值:“新模型,设计和产品”。

2.)当您通过urlopen()发送查询时,需要对查询进行URLEncode。

另外,articles将是一个词典,因此您需要使用[]来解决这些文章:

for story in articles["results"]: 

如果此处的查询不是您想要的,NYT有一个工具,可让您玩构建查询:NYT API Request Tool