首页 > 解决方案 > 请求库和除外

问题描述

大家。我从几个星期开始学习 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)

感谢您的建议。

标签: pythonpython-requests

解决方案


你需要做一个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 代码


推荐阅读