简体   繁体   English

Python 请求等待无响应

[英]Python Request Waits not Responding

import requests
res = requests.get("https://api.nasdaq.com/api/quote/list-type/nasdaq100")

When I enter url to browser it gives data, but when I use python it does not get data just waits.当我在浏览器中输入 url 时,它会提供数据,但是当我使用 python 时,它不会获取数据,只是等待。 Thanks.谢谢。

Seems like the user agent is the culprit after all:似乎用户代理毕竟是罪魁祸首:

>>> import requests
>>> requests.get("https://api.nasdaq.com/api/quote/list-type/nasdaq100", headers={"User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'})
<Response [200]>

Websites tend to block bots' and scrapers' user-agents.网站倾向于阻止机器人和爬虫的用户代理。 It is a common internet etiquette to respect their wishes.尊重他们的意愿是一种常见的互联网礼仪。

Seems like Nasdaq's API has free and premium tiers.似乎纳斯达克的 API有免费和高级等级。 I guess they wish programmatic Python users to obtain an API key.我猜他们希望编程 Python 用户获得 API 密钥。

Keep in mind they also have their own Python API .请记住,他们也有自己的Python API


Looks like Nasdaq's server leaves the connection open and gets stuck when a different user agent is sent.看起来纳斯达克的服务器使连接保持打开状态并在发送不同的用户代理时卡住。

Try switching between the commented and uncommented ssl.send() :尝试在注释和未注释ssl.send()之间切换:

import socket, ssl
context = ssl.create_default_context()
hostname = "api.nasdaq.com"
sock = socket.create_connection((hostname, 443))
ssl = context.wrap_socket(sock, server_hostname=hostname)
#ssl.send(b'GET /api/quote/list-type/nasdaq100 HTTP/1.1\r\nHost: api.nasdaq.com\r\nUser-Agent: python-requests/2.27.1\r\nAccept-Encoding: identity\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n')
ssl.send(b'GET /api/quote/list-type/nasdaq100 HTTP/1.1\r\nHost: api.nasdaq.com\r\nUser-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X);AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75;Mobile/14E5239e Safari/602.1\r\nAccept-Encoding: identity\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n')
print(ssl.recv(1024))

Faking request's user agent in chrome works though and returns a 403 unauthorized.在 chrome 中伪造请求的用户代理虽然有效,但返回 403 未授权。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM