首页 > 解决方案 > 当 url 无效时 Request.get 抛出 ConnectionError 并且 python 脚本终止

问题描述

正如标题所解释的那样;只要我有一个有效的 url,python 脚本就可以正常运行,一旦我将它切换到无效的 url,脚本就会退出并显示一条长错误消息。我最终希望程序继续检查连接。

这是一些示例代码: 适用于有效的 url

import requests
request = requests.get('http://www.example.com')
if request.status_code == 200:
   print('Web site exists')
else:
   print('Web site does not exist') 

使用无效的 url 不能按预期工作

import requests
request = requests.get('http://www.1337example.com')
if request.status_code == 200:
   print('Web site exists')
else:
   print('Web site does not exist') 

标签: pythonpython-requests

解决方案


它出错的原因是根本没有建立连接,这不允许python检查任何状态代码。因此错误出来了。

尝试除块可以解决这个问题

这将运行 try 块中的任何代码,然后在遇到任何错误时运行 except 块中的代码

try:
    request = requests.get('http://www.example.com')
    print('Web site exists')
except ConnectionError :
   print('Web site does not exist') 

编辑:添加了特定的例外


推荐阅读