python - 请求库和除外
问题描述
大家。我从几个星期开始学习 Python。我对请求库有疑问。我写了一个简短的代码,要求提供一个网站地址。如果页面存在,则将其写入文件 good.txt,如果不存在则应将其写入 wrong.txt 文件。这段代码有什么问题?
import requests
website = input('First website to check: ')
website1 = 'http://'+website
a = requests.get(website1)
try:
a.status_code == 200
with open("good.txt", "a", encoding = "UTF-8") as file:
file.write(website1)
except requests.RequestException:
with open("wrong.txt", "a", encoding = "UTF-8") as file:
file.write(website1)
感谢您的建议。
解决方案
你需要做一个if语句
try:
a = requests.get(website1)
if a.status_code == 200:
with open("good.txt", "a", encoding = "UTF-8") as file:
file.write(website1)
else:
with open("wrong.txt", "a", encoding = "UTF-8") as file:
file.write(website1)
except requests.RequestException:
with open("wrong.txt", "a", encoding = "UTF-8") as file:
file.write(website1)
编辑:还修复了您的 try catch 代码
推荐阅读
- typescript - 如何在 VS Code 中禁用不必要的自动完成建议?
- android - 当我通过意图打开 PDF 时,无法在 Android 中显示 PDF(无法打开)
- python - 使用python并行处理文件夹中的许多文件
- java - 如何在向量中的某处添加一个数字并将以下数字移动一个位置?
- ruby-on-rails - 类的实例方法
- python - 使用 lambda 函数创建新的数据框字段
- javascript - Express.js:全局错误处理程序中间件无法处理中间件中的抛出
- ios - 新版 Xcode 出现错误 65 怎么办?
- kotlin - Gradle,错误:找不到模块:kotlin.logging
- python-3.x - Python-OpenCV 中头部姿势的仰角如何工作?