尝试向 pypi 发出请求时出现 403 错误 api

403 error when trying to make requests to pypi api

我的代码:

import requests

x = requests.get('http://pypi.python.org/pypi/urllib3/json')

print(x)

输出:

<Response [403]>

为什么我会收到此响应,即使它在浏览器中运行良好?

我尝试打印 json:

import requests

x = requests.get('http://pypi.python.org/pypi/urllib3/json')

print(x.json())

但是它给了我一个错误:

Traceback (most recent call last):
  File "C:\Users\HP\Desktop\temp.py", line 5, in <module>
    print(x.json())
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py", line 900, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

应该是https而不是http

这会起作用。

import requests

x = requests.get('https://pypi.python.org/pypi/urllib3/json')
print(x)

json_str = x.json()
print(json_str)
<Response [200]>

{'info': {'author': 'Andrey Petrov', 'author_email': 'andrey.petrov@shazow.net', 'bugtrack_url': None,....}

改用 https://pypi.python.org/pypi/urllib3/json,它在我的电脑上运行良好。

from requests import get
url = 'https://pypi.python.org/pypi/urllib3/json'
result = get(url).json()