我最近一直在尝试制作一个程序,返回缩短的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
您正在请求一个不存在的url。因此,您将获得一个超时
主机是您传入的url。您可以捕获异常并查看您传入的相同url,但是您将url传递给了
requests.get
相关问题 更多 >
编程相关推荐