You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python requests.get解析API时遭遇权限访问错误

解决OTCMarkets API请求被拒绝的问题

我尝试从某API URL解析数据,在浏览器中打开该URL可以看到所需数据,但使用Python的requests库请求时,收到无权限访问的错误。

我的代码

import requests
url_screener = 'https://www.otcmarkets.com/research/stock-screener/api'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'}
response = requests.get(url_screener, headers=headers, stream=True)
print(response.text)

错误信息

<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>

You don't have permission to access "http&#58;&#47;&#47;www&#46;otcmarkets&#46;com&#47;research&#47;stock&#45;screener&#47;api" on this server.<P>
Reference&#32;&#35;18&#46;1cc68848&#46;1677748437&#46;31cb4c51
</BODY>
</HTML>

我尝试使用代理,但也无效。期望在Python中获取与浏览器相同的数据。


解决方法

  • 补充完整请求头:浏览器请求时会携带更多关键头信息,仅User-Agent不够,需添加Referer、Accept等字段,让请求更贴近浏览器行为:
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
    'Referer': 'https://www.otcmarkets.com/research/stock-screener',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9'
}
  • 使用会话维持状态:网站可能通过Cookie验证会话合法性,用requests.Session()可以自动管理Cookie,先访问API对应的页面获取必要Cookie,再请求API:
import requests

session = requests.Session()
# 设置统一请求头
session.headers.update({
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
    'Referer': 'https://www.otcmarkets.com/research/stock-screener',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9'
})

# 先访问股票筛选页面,获取会话Cookie
session.get('https://www.otcmarkets.com/research/stock-screener')

# 再发起API请求
response = session.get('https://www.otcmarkets.com/research/stock-screener/api')
print(response.text)
  • 核对请求参数:打开浏览器开发者工具的Network面板,查看浏览器请求该API时的完整URL(是否带查询参数)、请求方法等,确保Python请求和浏览器完全一致。

内容的提问来源于stack exchange,提问作者Shay Trip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:13:31