我最近一直在尝试制作一个程序,该程序使用 Python Requests 库返回缩短的 URL(例如 bit.ly 和 t.co URL)导致的 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?
Python
蟒蛇请求
http请求
米脂
相关分类