Checking if a website is up via Python

后端 未结 14 1996
南笙
南笙 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)
    
    0 讨论(0)
  • 2020-12-04 10:20

    my 2 cents

    def getResponseCode(url):
    conn = urllib.request.urlopen(url)
    return conn.getcode()
    
    if getResponseCode(url) != 200:
        print('Wrong URL')
    else:
        print('Good URL')
    
    0 讨论(0)
  • 2020-12-04 10:23
    from urllib.request import Request, urlopen
    from urllib.error import URLError, HTTPError
    req = Request("http://stackoverflow.com")
    try:
        response = urlopen(req)
    except HTTPError as e:
        print('The server couldn\'t fulfill the request.')
        print('Error code: ', e.code)
    except URLError as e:
        print('We failed to reach a server.')
        print('Reason: ', e.reason)
    else:
        print ('Website is working fine')
    

    Works on Python 3

    0 讨论(0)
  • 2020-12-04 10:23

    In my opinion, caisah's answer misses an important part of your question, namely dealing with the server being offline.

    Still, using requests is my favorite option, albeit as such:

    import requests
    
    try:
        requests.get(url)
    except requests.exceptions.ConnectionError:
        print(f"URL {url} not reachable")
    
    0 讨论(0)
  • 2020-12-04 10:27

    If server if down, on python 2.7 x86 windows urllib have no timeout and program go to dead lock. So use urllib2

    import urllib2
    import socket
    
    def check_url( url, timeout=5 ):
        try:
            return urllib2.urlopen(url,timeout=timeout).getcode() == 200
        except urllib2.URLError as e:
            return False
        except socket.timeout as e:
            print False
    
    
    print check_url("http://google.fr")  #True 
    print check_url("http://notexist.kc") #False     
    
    0 讨论(0)
  • 2020-12-04 10:27

    If by up, you simply mean "the server is serving", then you could use cURL, and if you get a response than it's up.

    I can't give you specific advice because I'm not a python programmer, however here is a link to pycurl http://pycurl.sourceforge.net/.

    0 讨论(0)
提交回复
热议问题