测试python3的互联网连接

时间:2018-05-28 01:18:54

标签: python-3.x networking

如何检查python3模块是否已连接到互联网?

我看到这是Python2的solution,并希望做类似的事情。

5 个答案:

答案 0 :(得分:2)

以下代码段对我有用。

from urllib.request import urlopen

def internet_on():
   try:
        response = urlopen('https://www.google.com/', timeout=10)
        return True
    except: 
        return False

其他用例可能需要改进错误处理和/或其他配置。

答案 1 :(得分:0)

如果在线,您还可以仅检查主机名: (有用的网址是API,需要POST而不是GET)

def have_internet(url):
   try:
      o = urlparse(url)
      response = urlopen(o.scheme+'://'+o.netloc, timeout=5)
      return True
   except:
      print('No access to',url)
      return False

答案 2 :(得分:0)

这是我的代码:

response = urlopen('https://www.google.com/', timeout=10)
print(response)
<http.client.HTTPResponse object at 0x0000024E196C9CC0>

所以..

import sys
from urllib.request import urlopen

response = urlopen('https://www.google.com/', timeout=10)

if response == "<http.client.HTTPResponse object at 0x0000024E196C9CC0>":
    print("Ok!")
else:
    print("NO!!!")

我该怎么办?

答案 3 :(得分:0)

这是针对python3的。我现在使用了一段时间。

import socket,time
mem1 = 0
while True:
    try:
            host = socket.gethostbyname("www.google.com") #Change to personal choice of site
            s = socket.create_connection((host, 80), 2)
            s.close()
            mem2 = 1
            if (mem2 == mem1):
                pass #Add commands to be executed on every check
            else:
                mem1 = mem2
                print ("Internet is working") #Will be executed on state change

    except Exception as e:
            mem2 = 0
            if (mem2 == mem1):
                pass
            else:
                mem1 = mem2
                print ("Internet is down")
    time.sleep(10) #timeInterval for checking

答案 4 :(得分:0)

我们使用以下代码测试互联网连接。当互联网连接或出现错误时,generate_204将在此处生成代码204。

import requests

url = 'http://clients3.google.com/generate_204'

try:
    response = requests.get(url, timeout=5)
    if response.status_code == 204:
        print(response.status_code)
        response.raise_for_status()
except requests.exceptions.RequestException as err:
    print("OOps: Something Else", err)
except requests.exceptions.HTTPError as errh:
    print("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
    print("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
    print("Timeout Error:", errt)