【发布时间】:2015-06-20 17:22:27
【问题描述】:
这与this 问题有关。我试图使用记录的parameters 查询 Glassdoor 公共 API,但一直收到 403 Forbidden 响应。为了确保正确使用查询参数来创建 URL,我采用了组合查询 URL 并在浏览器中进行了尝试,并且成功了。
从我的浏览器进行的查询向后工作,我设法弄清楚用户代理不仅需要作为 URL 中的参数,还需要在标头中传递。
综上所述,以下代码将成功查询 Glassdoor 公共 API:
import urllib.request as request
import requests
import json
from collections import OrderedDict
# authentication information & other request parameters
params_gd = OrderedDict({
"v": "1",
"format": "json",
"t.p": "xxxxxx",
"t.k": "yyyyyyyy",
"action": "employers",
"employerID": "11111",
# programmatically get the IP of the machine
"userip": json.loads(request.urlopen("http://ip.jsontest.com/").read().decode('utf-8'))['ip'],
"useragent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36"
})
# construct the URL from parameters
basepath_gd = 'http://api.glassdoor.com/api/api.htm'
# request the API
response_gd = requests.get(basepath_gd,
params=params_gd,
headers={
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36"
})
# check the response code (should be 200) & the content
response_gd
response_gd.content
我的问题是——当User-Agent 已经是 URL 参数的一部分时,为什么还需要在查询标头中指定它?如果没有用户代理标头,查询不应该工作吗?
【问题讨论】:
-
HTTP 标头与 API 提供者可能需要的
useragent标头无关。在这种情况下,似乎标头应该是 your 代理,而useragent参数应该是最终用户的代理。 -
@poke 我必须承认我对你的答案并不完全清楚,这可能是因为我对 REST 的理解不够好。您可以指出的任何参考资料将帮助我了解两者可能不同的部署场景?
-
@fgnu 很好的解决方案!这比 Glassdoor 官方文档效果更好。您能否详细说明您是如何“从浏览器进行的查询向后工作”的?
标签: python rest python-3.x python-requests