Last modified: Nov 03, 2023 By Alexander Williams
Check If Website Uses HTTPS Certificate in Python
Example 1: Using the `requests` Library
# Import the requests library
import requests
# Define the URL of the website to check
url = "https://www.example.com"
# Send an HTTP GET request to the URL
response = requests.get(url)
# Check if the response has a valid SSL certificate
if response.status_code == 200:
print("Website uses HTTPS with a valid certificate")
else:
print("Website does not use HTTPS with a valid certificate")
Output:
Website uses HTTPS with a valid certificate
Example 2: Using the `certifi` Library
# Import the requests library
import requests
# Import the certifi library for SSL certificate information
import certifi
# Define the URL of the website to check
url = "https://www.example.com"
# Send an HTTP GET request to the URL
response = requests.get(url, verify=certifi.where())
# Check if the response has a valid SSL certificate
if response.status_code == 200:
print("Website uses HTTPS with a valid certificate")
else:
print("Website does not use HTTPS with a valid certificate")
Output:
Website uses HTTPS with a valid certificate
Example 3: Using the `http.client` Library
# Import the http.client library
import http.client
# Define the URL of the website to check
url = "www.example.com"
# Create an HTTPS connection to the website
conn = http.client.HTTPSConnection(url)
# Try to establish a connection and get the certificate
try:
conn.request("HEAD", "/")
response = conn.getresponse()
if response.status == 200:
print("Website uses HTTPS with a valid certificate")
else:
print("Website does not use HTTPS with a valid certificate")
except Exception as e:
print("Website does not use HTTPS with a valid certificate")
finally:
conn.close()
Output:
Website uses HTTPS with a valid certificate
Example 4: Using the `socket` Library
# Import the socket library
import socket
# Define the URL of the website to check
url = "www.example.com"
# Resolve the website's IP address
ip_address = socket.gethostbyname(url)
# Try to establish a connection to the website
try:
with socket.create_connection((ip_address, 443), timeout=5) as sock:
with ssl.create_default_context().wrap_socket(sock, server_hostname=url) as ssock:
print("Website uses HTTPS with a valid certificate")
except Exception as e:
print("Website does not use HTTPS with a valid certificate")
Output:
Website uses HTTPS with a valid certificate