首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >请求库和except

请求库和except
EN

Stack Overflow用户
提问于 2021-04-05 03:28:52
回答 2查看 36关注 0票数 0

所有人。我花了几周的时间学习Python。我有一个关于请求库的问题。我写了一个简短的代码,要求输入网站地址。如果该页存在,则将其写入文件good.txt,如果该页不存在,则将其写入wrong.txt文件。这段代码有什么问题?

代码语言:javascript
复制
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)

谢谢你的建议。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-05 03:35:52

使用try/except块,您必须在try块中发出请求。

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2021-04-05 03:33:07

您需要创建一个if语句

代码语言:javascript
复制
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代码

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66945091

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档