Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用python检查用户是否连接到internet?_Python_Web Scraping_Urllib3 - Fatal编程技术网

如何用python检查用户是否连接到internet?

如何用python检查用户是否连接到internet?,python,web-scraping,urllib3,Python,Web Scraping,Urllib3,我是Python3.5,使用urllib3,我见过很多例子,但它们都是urllib2,这就是为什么我问这个问题,我有一些代码需要internet,但如果用户未连接,我想向他们显示一条警告,说明设备未连接到internet,那么我该如何操作。您可以在检查站点连接的情况下执行类似操作 import urllib.request import urllib.parse try: x = urllib.request.urlopen('https://www.google.com')

我是Python3.5,使用urllib3,我见过很多例子,但它们都是urllib2,这就是为什么我问这个问题,我有一些代码需要internet,但如果用户未连接,我想向他们显示一条警告,说明设备未连接到internet,那么我该如何操作。

您可以在检查站点连接的情况下执行类似操作

import urllib.request 
import urllib.parse 

try: 
    x = urllib.request.urlopen('https://www.google.com')        
except Exception as e: 
    print(str(e)) 

我以前没有使用过urllib,但您可以尝试以下方法:

try:
    #you put your code here
    #and it will raise an exception if
    #network connection is not available
    #so you catch that
except:
    #your warning code

您可以发布您迄今为止尝试过的代码吗?您提出请求并在异常出现时处理它。这是否回答了您的问题?不,因为我不知道urllib2,我正在使用URLLIB3,它可以与任何版本的
urllib
一起使用。