python - 通过 Web 连接到 API 与 Python

标签 python xml http

我正在尝试通过 API 访问 XML 文档。当我尝试在 python 中连接时,我收到 403 状态代码。但是,当我将链接粘贴到 Chrome 浏览器中时,数据会按应有的方式显示。我知道我可能需要在 Python 中添加一些 header 到我的请求中,但我不知道该怎么做。

schedule = requests.get('https://api.sportradar.us/golf-t2/schedule/pga/2015/tournaments/schedule.xml?api_key=mssbj55v2wbrbr6jcet2xcdd')
print(schedules.status_code)

我能够在 Chrome 中获取 header ,但不确定需要将哪些 header 添加到我的请求中

接受:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8

用户代理:Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,如 Gecko)Chrome/55.0.2883.87 Safari/537.36

如何调整我的请求才能返回状态 200?

最佳答案

将所有其他浏览器 header 添加到请求中。最简单的方法:在 Chrome 上打开链接,打开开发工具、网络选项卡,然后右键单击并“复制为 cURL”。粘贴到控制台并检查是否足够:

$ curl 'https://api.sportradar.us/golf-t2/schedule/pga/2015/tournaments/schedule.xml?api_key=mssbj55v2wbrbr6jcet2xcdd' -H 'Accept-Encoding: gzip, deflate, sdch, br' -H 'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,es;q=0.2' -H 'Upgrade-Insecure-Requests: 1' -H 'X-Compress: null' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Cache-Control: max-age=0' -H 'If-None-Match: "c97bea3f0b2917ae53554f338c416859"' -H 'Connection: keep-alive' -H 'If-Modified-Since: Wed, 07 Oct 2015 02:41:03 GMT' --compressed ;

输出:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:s="http://feed.elasticstats.com/schema/golf/schedule-v1.0.xsd"
            exclude-result-prefixes="s" version="1.0">

<xsl:output method="html" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
....

然后将 header 添加到您的应用程序中:

http://docs.python-requests.org/en/master/user/quickstart/#custom-headers

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}

>>> r = requests.get(url, headers=headers)

关于python - 通过 Web 连接到 API 与 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522947/

相关文章:

security - 是否可以在应用程序级别限制请求域?

node.js - 空 req.body 接收到 node.js 的文本/纯 POST 请求

python - Pandas 列对象分桶值提取

python - 说法1和说法2有什么区别吗

jquery - 使用 jquery ajax 将内容 append 到 div id

php - 如何将 SOAP 响应转换为 PHP 数组?

python - 绘制矩形 tkinter 不起作用

python - Numba 通过影响就地损坏数据

xml - 如何在R中打开文件格式和文件扩展名不同的excel文件?

http - Jmeter 在我的测试完成之前关闭连接