【问题标题】:Python - Request not authorized by using requests and jsonPython - 请求未使用请求和 json 授权
【发布时间】:2021-12-04 14:58:26
【问题描述】:

我一直在使用代码python来访问这种urlhttps://api.elsevier.com/analytics/scival/institution/metrics?metricTypes=ScholarlyOutput&institutionIds=508175%2C508076&yearRange=5yrs&includeSelfCitations=true&byYear=true&includedDocs=AllPublicationTypes&journalImpactType=CiteScore&showAsFieldWeighted=false&apiKey=7f59af901d2d86f78a1fd60c1bf9426a

这是Elsevier Developer Portal给出的公开json url

我一直在使用的小代码是这样的:

import requests
import json

url = "https://api.elsevier.com/analytics/scival/institution/metrics?metricTypes=ScholarlyOutput&institutionIds=508175%2C508076&yearRange=5yrs&includeSelfCitations=true&byYear=true&includedDocs=AllPublicationTypes&journalImpactType=CiteScore&showAsFieldWeighted=false&apiKey=7f59af901d2d86f78a1fd60c1bf9426a"

with requests.Session() as s:
    data = s.get(url).json()

直到今天我的项目在执行此代码时出现错误,一切都很好,如果我只运行s.get(url).text,那么我会收到以下消息 '请求未获授权。请指定有效的 API 密钥或 HMAC 签名。 我不得不说我什至有自己的 api_key 和 access_token,但即使使用它们我也会得到相同的消息。

所以,我需要一些帮助来管理提取数据,因为数据仍然在链接 https://api.elsevier.com/analytics/scival/institution/metrics?metricTypes=ScholarlyOutput&institutionIds=508175%2C508076&yearRange=5yrs&includeSelfCitations=true&byYear=true&includedDocs=AllPublicationTypes&journalImpactType=CiteScore&showAsFieldWeighted=false&apiKey=7f59af901d2d86f78a1fd60c1bf9426a 中(只需谷歌就会看到它)。 希望有一些指导来做到这一点,因为直到昨天都没有错误。

【问题讨论】:

    标签: python json url request


    【解决方案1】:

    我检查了文档,但您在请求中缺少标头。

    下面的代码正在运行。

    import requests
    
    url = "https://api.elsevier.com/analytics/scival/institution/metrics?metricTypes=ScholarlyOutput&institutionIds=508175%2C508076&yearRange=5yrs&includeSelfCitations=true&byYear=true&includedDocs=AllPublicationTypes&journalImpactType=CiteScore&showAsFieldWeighted=false&apiKey=7f59af901d2d86f78a1fd60c1bf9426a"
    
    payload={}
    headers = {
      'Accept': 'application/json'
    }
    
    response = requests.request("GET", url, headers=headers, data=payload)
    
    print(response.text)
    

    【讨论】:

    • 非常感谢。这很好用,虽然我仍然不知道为什么在它工作正常之前,今天出现错误。您能告诉我您在哪里找到要传递给请求函数的标头“类型”吗?
    • 在文档中他们写了传递标头的要求,他们还提供了 curl 命令,我在 postman 上导入 curl 命令并将 postman 集合转换为 python。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多