【发布时间】:2019-08-28 18:26:27
【问题描述】:
我正在尝试确定 python 中请求模块的错误处理,以便在 URL 不可用时得到通知,即 HTTPError、ConnectionError、Timeout 等...
我遇到的问题是,即使在 FAKE URL 上,我似乎也收到了 200 的状态响应
我浏览了 S.O.以及其他各种网络资源,尝试了许多不同的方法,看似试图实现相同的目标,但到目前为止都一无所获。
我已将代码简化为尽可能基本的代码。
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)
我希望列表中的前 3 个 URL 归类为 'Website Error:',因为它们是我刚刚编造的 URL。
列表中的最终 URL 显然是真实的,因此应该是唯一一个被列为 'Website Good:'
发生的情况是第一个 URL 产生了对代码的正确响应,因为它给出了 503 的响应代码,但根据 https://httpstatus.io/,接下来的两个 URL 根本不产生 status_code,而只显示 ERROR Cannot find URI. another-fake-website.com another-fake-website.com:80
所以我希望列表中除了最后一个 URL 之外的所有 URL 都显示为 'Website Error:'
输出
在树莓派中运行脚本时
Python 2.7.9 (default, Sep 26 2018, 05:58:52)
[GCC 4.9.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
('Website Error: ', 'http://fake-website.com', <Response [503]>)
('Website Good: ', 'http://another-fake-website.com', <Response [200]>)
('Website Good: ', 'http://yet-another-fake-website.com', <Response [200]>)
('Website Good: ', 'http://google.com', <Response [200]>)
>>>
如果我在https://httpstatus.io/ 中输入所有 4 个 URL,我会得到以下结果:
它显示一个 503、一个 200 和两个没有状态代码而只是显示错误的 URL
更新
所以我想我会在 Windows 中使用 PowerShell 进行检查并遵循以下示例: https://stackoverflow.com/a/52762602/5251044
这是下面的输出
c:\Testing>powershell -executionpolicy bypass -File .\AnyName.ps1
0 - http://fake-website.com
200 - http://another-fake-website.com
200 - http://yet-another-fake-website.com
200 - http://google.com
如你所见,我没有更进一步。
更新 2
与FozoroHERE 进行了进一步讨论并尝试了各种选项但看不到修复我想我会使用urllib2 而不是requests 尝试此代码
这是修改后的代码
from urllib2 import urlopen
import socket
urls = ['http://another-fake-website.com',
'http://fake-website.com',
'http://yet-another-fake-website.com',
'http://google.com',
'dskjhkjdhskjh.com',
'doioieowwros.com']
for url in urls:
try:
r = urlopen(url, timeout = 5)
r.getcode()
except:
pass
if r.getcode() != 200:
print ("Website Error: ", url, r.getcode())
else:
print ("Website Good: ", url, r.getcode())
不幸的是,结果输出仍然不正确但确实与之前代码的输出略有不同,见下文:
Python 2.7.9 (default, Sep 26 2018, 05:58:52)
[GCC 4.9.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
('Website Good: ', 'http://another-fake-website.com', 200)
('Website Good: ', 'http://fake-website.com', 200)
('Website Good: ', 'http://yet-another-fake-website.com', 200)
('Website Good: ', 'http://google.com', 200)
('Website Good: ', 'dskjhkjdhskjh.com', 200)
('Website Good: ', 'doioieowwros.com', 200)
>>>
这次它显示了所有200的回复,非常奇特。
【问题讨论】:
标签: python python-2.7 python-requests