【问题标题】:How to check if user is connected to internet in python?如何检查用户是否在python中连接到互联网?
【发布时间】:2020-08-29 18:13:23
【问题描述】:

我是 python 3.5 并使用 urllib3,我看过各种示例,但它们是 urllib2 这就是我问这个问题的原因,我有一些需要互联网的代码,但如果用户未连接,我想向他们显示警告该设备未连接到互联网,所以我该怎么做。

【问题讨论】:

  • 您能发布到目前为止您尝试过的代码吗?
  • 您提出请求并在引发异常后处理它。
  • 这能回答你的问题吗? Checking network connection
  • 不,因为我不知道 urllib2,我正在使用 urllib3
  • 它适用于任何版本的urllib

标签: python web-scraping urllib3


【解决方案1】:

您可以在检查与网站的连接时执行类似的操作。

import urllib.request 
import urllib.parse 

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

【讨论】:

    【解决方案2】:

    我之前没用过 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
    

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 2015-05-25
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多