python - 当网站无法访问时,Python 会抛出错误
问题描述
我有以下代码来检查特定网站是否可用。
import urllib.request
with open("addresses.txt") as file:
url_list = file.read()
url_list = url_list.splitlines()
print("Chcking the repsonse code for the webiste")
for url in url_list:
response = urllib.request.urlopen(url).getcode()
response = (f"{response} available")
if "200 available" in response:
print(f"{url} is up and running")
else:
print(f"{url} is not reachable")
代码可以正常工作,直到网站可以访问,但如果网站关闭,它不会打印出“google.com 无法访问”的消息,而是会引发错误。 错误
抱歉,如果代码不是那么专业,我是 python 新手,所以在这里任何帮助都会有所帮助。
解决方案
你可能想做这样的事情:
try:
response = urllib.request.urlopen(url).getcode()
response = (f"{response} available")
if "200 available" in response:
print(f"{url} is up and running")
else:
print(f"{url} is not reachable")
except Exception as ex:
print(f"Attempting to contact {url} led to error:\n{ex}")
推荐阅读
- sql - 根据另一个更新列
- ssrs-2008 - 用于 SSRS 的自定义日期格式 iseries 访问 odbc
- ml.net - Microsoft.ML --version 0.3.0 -- 无法在 10 分钟内开始使用 ML.NET
- c# - 将图像(jpg)转换为 video.avi 在 IIS 中不起作用
- google-maps - 如何将 360 度图像导出到谷歌地图街景
- python - f-strings 是 python(3.6 及更高版本)的独特功能吗?
- angular - Angular 4 - 为应用程序组件使用解析器
- php - 如何在 Laravel 5.6 的索引页面中只显示一张图片?
- javascript - 如何更改点击切换?- 隐藏取消绑定按钮上的元素
- jquery - 未定义记录器,Google Apps 脚本