【发布时间】: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