我有自己的域,其中存储了一个 json 文件 (http://example.com/file.json)
。使用直接链接在浏览器中访问文件时,返回 json 就好了。但是当在我下面的 python 代码中使用相同的方法时,http 响应是 406。有什么想法吗?
import requests
url = 'http://example.com/file.json'
r = requests.get(url, headers={"Accept":"text/html"})
print(r.status_code)
print(r.headers)
打印:
406
{'Server': 'nginx/1.14.1', 'Date': 'Sun, 12 May 2019 16:53:25 GMT', 'Content-Type': 'text/html; charset=iso-8859-1', 'Content-Length': '226', 'Connection': 'k
eep-alive'}
最佳答案
通过使用不同的用户代理解决。默认的 Python 用户代理 'python-requests/2.21.0'
可能被托管公司阻止了。
r = requests.get(url, headers={"User-Agent": "XY"})
一些可能的代理人:List of User Agent strings
关于Python 请求 HTTP 响应 406,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56101612/