Python请求超时不适用于站点流

2024-09-28 22:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

以下内容适用于99.999%的网站,但随机发现了一个不适用的网站:

import requests
requests.get('http://arboleascity.com',timeout=(5,5),verify=False)

我对这个项目提出了异议。在

https://github.com/requests/requests/issues/4276

有什么建议或想法吗?在

我在concurrent.futures.ThreadPoolExecutor中运行这个,所以我不想添加一些外部的东西,比如eventlet或signals。但对任何有效的东西都要敞开心扉。在


Tags: 项目httpsimportgithubcomfalsehttpget
3条回答

问题不在于requests,而在于您访问特定站点的方式。在

也就是说,似乎http://arboleascity.com使用User-Agent头字段来区分浏览器和音乐播放器。在

如果使用有效的浏览器签名,它只返回页面HTML(text/html)并关闭连接:

$ curl -vvv -A 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0' http://arboleascity.com >/dev/null
...
< Content-Type: text/html;charset=utf-8
...
100   118    0   118    0     0    297      0  : :   : :   : :    297
* Connection #0 to host arboleascity.com left intact

但是,如果未定义User-Agent(默认值),则站点流二进制内容(audio/aacp)为~8kbps:

^{pr2}$

或者,with ^{}

>>> headers = {'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0'}
>>> r = requests.get('http://arboleascity.com', headers=headers)

他们都在工作。在

The connect timeout is the number of seconds Requests will wait for your client to establish a connection to a remote machine (corresponding to the connect()) call on the socket. It's a good practice to set connect timeouts to slightly larger than a multiple of 3, which is the default TCP packet retransmission window.

Once your client has connected to the server and sent the HTTP request, the read timeout is the number of seconds the client will wait for the server to send a response. (Specifically, it's the number of seconds that the client will wait between bytes sent from the server. In 99.9% of cases, this is the time before the server sends the first byte).

它流一个SHOUTcast流(内容类型:audio/aacp),所以没有超时,只是从不停止流。在

如果需要主页,而不是流,请将User-Agent头设置为类似于浏览器的内容。如果您需要音频流,请使用stream=True并迭代内容-在这里,如果需要,您也可以退出。在

如果您正在编写scraper,那么在尝试获取分块的响应之前,可能需要检查HEAD请求中的内容类型。在

相关问题 更多 >