您好,我面临的问题是,我想检查我的网站是否正常,这是示例伪代码
Check(website.com)
if checking_time > 10 seconds:
print "No response Recieve"
else:
print "Site is up"我已经尝试了下面的代码,但不起作用
try:
response = urllib.urlopen("http://insurance.contactnumbersph.com").getcode()
time.sleep(5)
if response == "" or response == "403":
print "No response"
else:
print "ok"发布于 2019-09-05 18:54:37
如果网站未启动并运行,您将收到连接被拒绝的错误,并且实际上不会返回任何状态代码。因此,您可以使用简单的try:和except:块来捕获python中的错误。
import requests
URL = 'http://some-url-where-there-is-no-server'
try:
resp = requests.get(URL)
except Exception as e:
# handle here
print(e) # for example也可以重复检查10次,每次每秒检查是否有异常,如果有则再次检查
import requests
URL = 'http://some-url'
canCheck = False
counts = 0
gotConnected = False
while counts < 10 :
try:
resp = requests.get(URL)
gotConnected = True
break
except Exception as e:
counts +=1
time.sleep(1)结果将在gotConnected标志中可用,您可以稍后使用它来处理适当的操作。
发布于 2019-09-05 22:04:37
请注意,由urllib传递的timeout应用于"wrong thing“。也就是说,每个单独的网络操作(例如,主机名解析、套接字连接、发送报头、读取几个字节的报头、读取更多几个字节的响应)都会应用相同的超时。因此,传递10秒的“超时”可以使大型响应持续数小时。
如果你想坚持使用内置的Python代码,那么使用线程来做这件事是很好的,但是似乎不可能很好地cancel running threads。像trio这样的异步库可以提供更好的timeout and cancellation handling,但我们也可以使用multiprocessing模块来凑合使用:
from urllib.request import Request, urlopen
from multiprocessing import Process
from time import perf_counter
def _http_ping(url):
req = Request(url, method='HEAD')
print(f'trying {url!r}')
start = perf_counter()
res = urlopen(req)
secs = perf_counter() - start
print(f'response {url!r} of {res.status} after {secs*1000:.2f}ms')
res.close()
def http_ping(url, timeout):
proc = Process(target=_http_ping, args=(url,))
try:
proc.start()
proc.join(timeout)
success = not proc.is_alive()
finally:
proc.terminate()
proc.join()
proc.close()
return success您可以使用https://httpbin.org/来测试这一点,例如:
http_ping('https://httpbin.org/delay/2', 1)应该打印出“正在尝试”的消息,而不是“响应”的消息。您可以调整延迟时间和超时,以了解这是如何运行的...
请注意,这会为每个请求创建一个新进程,但只要每秒执行的ping数少于1000次,就应该没问题
https://stackoverflow.com/questions/57803725
复制相似问题