【问题标题】:https Get request failing on first try - python requesthttps 获取请求第一次尝试失败 - python 请求
【发布时间】:2021-07-07 17:09:00
【问题描述】:

在 api.nasdaq.com 上执行 GET 请求时,我收到错误响应 400 - 该请求的标头名称无效。 但是如果我在浏览器中点击相同的 URL,它确实会返回一个有效的响应。

在通过浏览器点击 url 之后,下面的代码也可以正常工作。如果我对符号变量使用新值,那么它再次失败并显示 400 。每次我在浏览器中尝试 url 然后运行此代码时它都可以工作,但不是第一次。

这种行为是由于任何 cookie 的使用造成的吗?任何帮助表示赞赏。

import requests

symbol = 'ALB'
url = "https://api.nasdaq.com/api/quote/{}/historical?assetclass=stocks&fromdate=2021-07-06&todate=2021-07-07".format(symbol)
headers = {
                "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                "Accept-Encoding":"gzip, deflate, br",
                "Accept-Language":"en-US,en;q=0.9",
                "Connection":"keep-alive",
                "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36",
                "cache - control":"max-age=0, no-cache, no-store",
                "upgrade-insecure-requests": "1"
    }
response = requests.get(url, headers = headers, verify=True)
if response.status_code != 200:
    print("download response code:{}".format(response.status_code))
    print("download response text:{}".format(response.text))
else:
    print(response.text)

失败响应:

download response code:400
download response text:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>

可以用来测试的各种符号是 AMZN、AAPL、MSFT、ALB、ABC、SQ

【问题讨论】:

  • 注释掉 User-Agent 并告诉我它是否有效

标签: python python-requests httpcookie


【解决方案1】:

使用这些标头可以得到 200 响应。我利用缓存控制和升级不安全请求。

很遗憾,我无法帮助您解决 cookie 使用问题。

headers = {
                "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                "Accept-Encoding":"gzip, deflate, br",
                "Accept-Language":"en-US,en;q=0.9",
                "Connection":"keep-alive",
                "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36",
                "Cache-Control":"max-age=0, no-cache, no-store",
                "Upgrade-Insecure-Requests": "1"
    }

【讨论】:

  • @MadhaviD np,你能把它标记为最终选择吗?
猜你喜欢
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 2011-09-12
  • 1970-01-01
相关资源
最近更新 更多