通过请求访问API,但在Python中出现错误

时间:2019-06-30 21:30:05

标签: python python-3.x jupyter-notebook

我正在尝试访问API,并且提到它以HTML形式提供。我经历了这些答案

Get html using Python requests?),但我没有得到结果。我只是想确保在遇到这样的错误时能够正确执行(“” {"request":{"category_id":"717234","command":"category"},"data":{"error":"invalid or missing api_key'"这个API不起作用?是否有任何方法可以获取HTML数据并将其转换为CSV或excel? 这是我正在使用的代码。

import requests
URL = "https://api.eia.gov/category?api_key=YOUR_API_KEY_HERE&category_id=717234"
r = requests.get(url = URL)
r.text[:100]

2 个答案:

答案 0 :(得分:1)

您使用的API无效,因此指向html页面的链接无效:

import requests
URL = "https://api.eia.gov/category?api_key=YOUR_API_KEY_HERE&category_id=717234"
headers = {'Accept-Encoding': 'identity'}
r = requests.get(URL, headers=headers)
print(r.text[:100])

输出:

{"request":{"category_id":"717234","command":"category"},"data":{"error":"invalid or missing api_key

我尝试使用您放入链接的答案中给出的那个链接来更改链接的链接,然后得到结果:

import requests
URL = "http://www.wrcc.dri.edu/WRCCWrappers.py?sodxtrmts+028815+por+por+pcpn+none+mave+5+01+F"
headers = {'Accept-Encoding': 'identity'}
r = requests.get(URL, headers=headers)
print(r.text[:100])

输出:

<!DOCTYPE html>
<HTML>
<HEAD><TITLE>Average of Precipitation, Station id: 028815</TITLE></HEAD>
<BO

作为解决方案,您可以使用外部api的devoloper模式:https://www.eia.gov//developer//或检查此链接以获取密钥:https://www.eia.gov/opendata/

答案 1 :(得分:0)

这不是错误。
在我看来,您好像缺少您的API密钥。

这是您在链接中写的内容:

{"request":{"category_id":"717234","command":"category"},"data":{"error":"invalid or missing api_key. For key registration, documentation, and examples see https:\/\/www.eia.gov\/developer\/"}}