ConnectionError 后如何获取请求的 URL?

我最近一直在尝试制作一个程序,该程序使用 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请求


慕尼黑5688855
浏览 230回答 1
1回答

米脂

您正在请求一个不存在的 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:...&nbsp; &nbsp; &nbsp;requests.get('https://does-not-exist')... except requests.exceptions.ConnectionError as error:...&nbsp; &nbsp; &nbsp;print(error.request.url)...https://does-not-exist/
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python