所有人。我花了几周的时间学习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)谢谢你的建议。
发布于 2021-04-05 03:35:52
使用try/except块,您必须在try块中发出请求。
import requests
website = input('First website to check: ')
website1 = 'http://'+website
try:
a = requests.get(website1)
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)发布于 2021-04-05 03:33:07
您需要创建一个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代码
https://stackoverflow.com/questions/66945091
复制相似问题