Checking if a website is up via Python

后端 未结 14 2048
南笙
南笙 2020-12-04 09:27

By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?

14条回答
  •  爱一瞬间的悲伤
    2020-12-04 10:17

    Hi this class can do speed and up test for your web page with this class:

     from urllib.request import urlopen
     from socket import socket
     import time
    
    
     def tcp_test(server_info):
         cpos = server_info.find(':')
         try:
             sock = socket()
             sock.connect((server_info[:cpos], int(server_info[cpos+1:])))
             sock.close
             return True
         except Exception as e:
             return False
    
    
     def http_test(server_info):
         try:
             # TODO : we can use this data after to find sub urls up or down    results
             startTime = time.time()
             data = urlopen(server_info).read()
             endTime = time.time()
             speed = endTime - startTime
             return {'status' : 'up', 'speed' : str(speed)}
         except Exception as e:
             return {'status' : 'down', 'speed' : str(-1)}
    
    
     def server_test(test_type, server_info):
         if test_type.lower() == 'tcp':
             return tcp_test(server_info)
         elif test_type.lower() == 'http':
             return http_test(server_info)
    

提交回复
热议问题