Чтобы проверить, есть ли в системе подключение к Интернету с помощью Python, вы можете использовать различные методы. Вот несколько подходов:
Метод 1: использование модуля socket
import socket
def check_internet_connection():
try:
# Attempt to connect to a well-known website
socket.create_connection(("www.google.com", 80))
return True
except OSError:
pass
return False
Метод 2. Использование модуля urllib
import urllib.request
def check_internet_connection():
try:
# Attempt to access a website
urllib.request.urlopen("http://www.google.com", timeout=1)
return True
except urllib.request.URLError:
pass
return False
Метод 3. Использование библиотеки requests
(необходимо установить)
import requests
def check_internet_connection():
try:
# Send a GET request to a website
response = requests.get("http://www.google.com", timeout=1)
response.raise_for_status() # Raise an exception for 4xx or 5xx status codes
return True
except requests.RequestException:
pass
return False
Обратите внимание, что для третьего метода вам необходимо установить библиотеку requests
. Вы можете установить его с помощью команды pip install Requests
.