小编1cm*_*m69的帖子

当 URL 不存在时 Python 请求模块中的错误处理

我正在尝试确定 python 中请求模块的错误处理,以便在 URL 不可用时收到通知,即 HTTPError、ConnectionError、Timeout 等...

我遇到的问题是,即使在假 URL 上,我似乎也收到了 200 的状态响应

我已经浏览了 SO 和其他各种网络资源,尝试了许多不同的方法来似乎试图实现相同的目标,但到目前为止都是空的。

我已经将代码简化为基本的代码,以简化事情。

import requests

urls = ['http://fake-website.com', 
        'http://another-fake-website.com',
        'http://yet-another-fake-website.com',
        'http://google.com']

for url in urls:
    r = requests.get(url,timeout=1)
    try:
        r.raise_for_status()
    except:
        pass
    if r.status_code != 200:
        print ("Website Error: ", url, r)
    else:
        print ("Website Good: ", url, r)
Run Code Online (Sandbox Code Playgroud)

我希望列表中的前 3 个 URL 被归类为'Website Error:'我刚刚创建的 URL。列表中的最终 URL 显然是真实的,因此应该是唯一一个被列为'Website Good:'

正在发生的事情是第一个URL生成的代码正确的响应,因为它给出了503的响应代码,但接下来的两个网址不产生status_code在所有根据https://httpstatus.io/,但只显示ERRORCannot find URI. another-fake-website.com another-fake-website.com:80

所以我希望列表中除了最后一个 URL 之外的所有 …

python python-2.7 python-requests

5
推荐指数
1
解决办法
1699
查看次数

标签 统计

python ×1

python-2.7 ×1

python-requests ×1