Skip to main content
 首页 » 编程设计

python之纽约时报 API, python

2025年05月04日10pengyingh

您好,我想从 NYtimes API 获取“title”之后的所有信息,这是我的代码

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 

如何解决问题?

请您参考如下方法:

我怀疑你想要的是:

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 :

Facets can be thought of as search "perspectives." With facets, you can look at search results from different perspectives, and you can approach your search queries from different angles. Each facet can be seen as representing a property or characteristic of Times article data.

Facets can reveal points of commonality and distinction that are not immediately apparent. For example, two articles with the word "bicycle" in the title may have two very different nytd_section_facet (NYTimes.com section) values: "Movies" and "Health." Similarly, two articles that discuss seemingly disparate topics, such as cloud computing and auto shows, may share a des_facet (descriptive subject term) value: "NEW MODELS, DESIGN AND PRODUCTS."

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

此外,articles 将是一个字典,因此您需要使用 [] 获取文章:

for story in articles["results"]:  

如果这里的查询不是您想要的,NYT 有一个工具可以让您尝试构建您的查询:NYT API Request Tool .