ping
# -*- coding:utf-8 -*- import os import time import datetime import subprocess retrytime = 0 def mprint(str): print "############# " + str.decode('utf-8') + " #############" def mNetPing(pingUrl): # mNetPing('jd.com') global retrytime print "开始检查网络状况,请耐心等待".decode('utf-8') p = subprocess.Popen(["ping.exe", pingUrl], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out = p.stdout.read() # print out out = out.decode('GB2312').encode('utf-8') # 转成utf8方便比较 if "(0% 丢失)" in out:#不能用 0% 丢失 因为100% 丢失包含 0% 丢失 刚好0的左边是10 所以改成(0%是可以的 加个括号 mprint("#############################网络正常#############################") elif "(100% 丢失)" in out:#网线连接正常 无法访问域名 mprint("#####################域名故障,请检查电脑能否访问 www.jd.com##################") os.system("pause") mNetPing(pingUrl) elif "找不到主机" in out:#网线断开 mprint("###########################请检查本机网络是否正常连接 3秒后自动重新检测###########################") time.sleep(3) retrytime = retrytime + 1 #os.system("pause") mprint("第"+str(retrytime)+"次重试") mNetPing(pingUrl) else:#请求超时 mprint("网络不稳定 是否继续?按任意键继续") os.system("pause") # print chardet.detect(out.decode('GB2312').encode('utf-8')) # mlost="100% 丢失".decode('utf-8') # print chardet.detect(mlost) # print mlost if __name__ == '__main__': # os.system("pause") print time.localtime()#<type 'time.struct_time'> print time.strftime('%Y-%m-%d', time.localtime(time.time())) print time.strftime('%H:%M:%S', time.localtime(time.time())) print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) mNetPing('jd.com') mprint("程序测试结束")
我在京东爬虫中用的到判断网络状况的代码,核心代码如下:
p = subprocess.Popen(["ping.exe", pingUrl], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out = p.stdout.read()
再根据out的内容自己判断吧!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异