如果网址无效,则Request.get引发ConnectionError并且python脚本终止

时间:2020-07-20 01:44:08

标签: python python-requests

正如标题所述;只要我有一个有效的url,python脚本就可以正常运行,一旦我将其切换为无效的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') 

使用无效的网址无法正常工作

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') 

1 个答案:

答案 0 :(得分:0)

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

尝试除块可以解决该问题

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

<Input value={null} />

编辑:添加了特定的例外情况

相关问题