Checking if a website is up via Python

后端 未结 14 2038
南笙
南笙 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:15

    Requests and httplib2 are great options:

    # Using requests.
    import requests
    request = requests.get(value)
    if request.status_code == 200:
        return True
    return False
    
    # Using httplib2.
    import httplib2
    
    try:
        http = httplib2.Http()
        response = http.request(value, 'HEAD')
    
        if int(response[0]['status']) == 200:
            return True
    except:
        pass
    return False
    

    If using Ansible, you can use the fetch_url function:

    from ansible.module_utils.basic import AnsibleModule
    from ansible.module_utils.urls import fetch_url
    
    module = AnsibleModule(
        dict(),
        supports_check_mode=True)
    
    try:
        response, info = fetch_url(module, url)
        if info['status'] == 200:
            return True
    
    except Exception:
        pass
    
    return False
    

提交回复
热议问题