为了账号安全,请及时绑定邮箱和手机立即绑定

ConnectionError 后如何获取请求的 URL?

ConnectionError 后如何获取请求的 URL?

慕尼黑5688855 2022-06-22 20:41:17
我最近一直在尝试制作一个程序,该程序使用 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.urlexcept requests.exceptions.ConnectionError as error:    fullUrl = "http://" + error.host但是,该方法不起作用(AttributeError: 'ConnectTimeout' object has no attribute 'host')。有什么方法可以让我从错误中获取缩短的 URL 重定向到的 URL?Python蟒蛇请求http请求
查看完整描述

1 回答

?
米脂

TA贡献1836条经验 获得超3个赞

您正在请求一个不存在的 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/


查看完整回答
反对 回复 2022-06-22
  • 1 回答
  • 0 关注
  • 229 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号