You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python检测网站是否正常运行?解决SSL证书验证错误问题

Hey there! Let's break down exactly why you're hitting that SSL error, then fix your script to do proper website availability checks the right way.

Why That SSL Error Is Happening

First, let's look at the error message you shared:

HTTPSConnectionPool(host='gooogle.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError("hostname 'gooogle.com' doesn't match 'www.google.com'")))

The core issue here is a misspelled domain (gooogle.com has an extra 'o') combined with how SSL certificates work. When you visit an HTTPS site, the server sends a certificate tied to specific valid domain names (like www.google.com or google.com). Since gooogle.com isn't one of those valid names, Python's requests library correctly throws an error to protect you from potential security risks (like a man-in-the-middle attack).

Even if you fix the spelling, you might run into similar SSL errors for domains without a valid, trusted SSL certificate—but in your case, it's purely a typo.

Fixing the Script & Proper Availability Checks

Your basic idea is solid, but we need to add better input handling, error catching, and more efficient practices. Here's an improved version of your code with explanations:

import requests
from requests.exceptions import RequestException, SSLError, ConnectionError, Timeout

def check_website_availability(url):
    # Normalize the input URL to ensure it has a valid protocol
    if not url.startswith(('http://', 'https://')):
        url = f'https://{url}'
    
    try:
        # Use HEAD instead of GET to save bandwidth (we only need status code/headers)
        response = requests.head(url, timeout=5, allow_redirects=True)
        
        # Any 2xx status code means the site is reachable and functioning
        if response.status_code // 100 == 2:
            return f"Good News, {url} is up and running!"
        else:
            return f"Warning: {url} is reachable but returned status code {response.status_code}"
    
    except SSLError as e:
        return f"SSL Error accessing {url}: {str(e)}\nThis often happens if the domain is misspelled, has an invalid SSL certificate, or uses a self-signed cert."
    except ConnectionError:
        return f"Connection Error: Could not reach {url} — double-check the domain or try again later."
    except Timeout:
        return f"Timeout Error: {url} took longer than 5 seconds to respond."
    except RequestException as e:
        return f"Unexpected error checking {url}: {str(e)}"

if __name__ == "__main__":
    website_url = input("Enter a website URL: ").strip()
    result = check_website_availability(website_url)
    print(result)

Key Improvements:

  • Input Normalization: Automatically adds https:// if the user doesn't include a protocol (prevents issues like trying to hit https://https://google.com).
  • HEAD Requests: Faster and lighter than GET because we don't download the entire page content—we just check if the server responds.
  • Comprehensive Error Handling: Catches specific exceptions for SSL issues, connection failures, timeouts, and other general errors, giving clear, actionable messages.
  • Broader Success Check: Instead of only checking for 200, we look for any 2xx status code (like 201, 204) since many valid sites return these for successful requests.

Extra Tips for Reliable Checks

  • Retry Logic: For production use, add retry mechanisms for transient errors (e.g., temporary network blips). You can use the tenacity library or configure requests's HTTPAdapter to retry failed requests.
  • DNS Validation: Before sending an HTTP request, you can use Python's socket module to check if the domain resolves to an IP address (this catches typos early).
  • Avoid verify=False: It's tempting to disable SSL verification to bypass errors, but this makes your requests vulnerable to attacks. Only use it for internal, trusted sites with self-signed certificates.

内容的提问来源于stack exchange,提问作者Kirito-Kun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:03:08