urllib.request HTTPError:未经授权

时间:2018-04-13 23:31:40

标签: python python-3.x urllib

我遇到了这个代码的问题。我有一个Http请求,我需要从API请求一些信息。我遇到了urllib请求的麻烦,我不认为我使用的是正确的库因为我得到它的代码使用urllib2 put因为python 3不同我不知道使用哪一个。

import urllib.request
import json
import os
from pprint import pprint

REST_URL = "http://data.bioontology.org"
API_KEY = "MYAPIKEY"

def get_json(url):
    opener = urllib.request.urlopen(url)
    opener.addheaders = [('Authorization', 'apikey token=' + API_KEY)]
    return json.loads(opener.open(url).read())
    print(url)

# Get list of search terms
path = os.path.join(os.path.dirname("__file__"), 'classes_search_terms.txt')
terms_file = open(path, "r")
terms = []
for line in terms_file:
    terms.append(line)

# Do a search for every term
search_results = []
for term in terms:
    search_results.append(get_json(REST_URL + "/search?q=" + term)["collection"])

# Print the results
for result in search_results:
    pprint(result)

0 个答案:

没有答案