python - 当 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')
解决方案
它出错的原因是根本没有建立连接,这不允许python检查任何状态代码。因此错误出来了。
尝试除块可以解决这个问题
这将运行 try 块中的任何代码,然后在遇到任何错误时运行 except 块中的代码
try:
request = requests.get('http://www.example.com')
print('Web site exists')
except ConnectionError :
print('Web site does not exist')
编辑:添加了特定的例外
推荐阅读
- python - 循环列表切片+元素分配Python
- ruby-on-rails - 是否可以使用 sdk gem 将账单应用到贝宝?
- javascript - 如何在网站上添加实时代码编辑器?
- node.js - Node.js中I/O密集是什么意思
- python - 创建一个新列 PySpark SQL - Python
- r - 注释图形更改ggplot2中的图例
- python - 将模型拟合到新数据集会覆盖以前的训练进度吗?
- python - 是否可以针对 2 个变量测试布尔值?
- c++ - 使用 while 循环输出数据,但它跳过了输出所需的第一个数字。程序非常接近正常工作,但无法正常工作
- python - 如何解决 Pandas 读取 json 类型错误?