在连接错误之后,如何获取请求的URL?

2024-10-03 00:17:53 发布

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

我最近一直在尝试制作一个程序,返回缩短的URL(如bit.ly和t.co URL)导致使用Python请求库的URL。我已经能够使用此方法轻松地处理URL:

reveal = requests.get(shortenedUrl, timeout=5)
fullUrl = reveal.url

但是,当缩短的URL指向一个不真实的URL(例如:http://thisurldoesnotexistyet.com/)时,上述方法按预期返回ConnectionError。ConnectionError返回以下内容: HTTPSConnectionPool(host='thisurldoesnotexistyet.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x00000213DC97F588>, 'Connection to thisurldoesnotexistyet.com timed out. (connect timeout=5)'))

发生这种情况时,我尝试使用此方法获取重定向URL:

try:
    reveal = requests.get(shortenedUrl, timeout=5)
    fullUrl = reveal.url
except requests.exceptions.ConnectionError as error:
    fullUrl = "http://" + error.host

但是,该方法不起作用(AttributeError: 'ConnectTimeout' object has no attribute 'host')。有没有办法从错误中获取缩短的URL重定向到的URL


Tags: 方法comhttphosturlgetobjecttimeout
1条回答
网友
1楼 · 发布于 2024-10-03 00:17:53

您正在请求一个不存在的url。因此,您将获得一个超时

>>> requests.get('https://does-not-exist')
... (suppressed for clarity)
requests.packages.urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='does-not-exist', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6b6dba7210>: Failed to establish a new connection: [Errno -2] Name or service not known'))

主机是您传入的url。您可以捕获异常并查看您传入的相同url,但是您将url传递给了requests.get

>>> try:
...     requests.get('https://does-not-exist')
... except requests.exceptions.ConnectionError as error:
...     print(error.request.url)
...
https://does-not-exist/

相关问题 更多 >