首页 > 解决方案 > Python 请求在读取时挂起

问题描述

我正在使用 Python 3.7.3,并且正在尝试获取 gif:

import requests
requests.get("https://track.hubspot.com", allow_redirects=True)

这段代码显然无限期地挂起。

import requests
requests.get("https://track.hubspot.com", allow_redirects=True, timeout=0.1)

此代码在读取时引发错误:ReadTimeout: HTTPSConnectionPool(host='track.hubspot.com', port=443): Read timed out. (read timeout=0.1)

如果我在浏览器中访问它,我会成功在目标上加载 1x1 gif。urllib3并且wget(命令行工具,而不是 Python 库)也挂起。有没有办法使用 Python 获取地址而不会出现任意超时和错误?

标签: pythonpython-requestshttp-get

解决方案


这对我有用response = requests.get('https://track.hubspot.com')
你应该考虑使用上下文管理器。

with requests.Session() as session:
    response = session.get("https://track.hubspot.com")

推荐阅读