如何用python检查用户是否连接到internet?
我是Python3.5,使用urllib3,我见过很多例子,但它们都是urllib2,这就是为什么我问这个问题,我有一些代码需要internet,但如果用户未连接,我想向他们显示一条警告,说明设备未连接到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')
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
一起使用。