如何在Whois查询中跳过不含指定变量的域名避免报错?
解决Whois查询中缺失字段的KeyError问题
当部分域名的Whois查询结果不含指定字段(如emails)时,直接通过res['字段名']访问会触发KeyError,你可以通过以下两种方式避免错误,实现缺失字段时跳过打印或显示默认信息:
方法1:使用字典的get()方法
dict.get(key, default)方法会在键存在时返回对应值,不存在时返回指定的默认值(默认是None),不会抛出错误。修改代码如下:
import whois def whodata(host): res = whois.whois(host) print(res['registrar']) # 存在则打印邮箱,不存在则打印提示文本 print(res.get('emails', '无可用邮箱信息')) print(res['country']) print("---------") test = ["minecraft.net", "google.com",'mob1lebn1-co.id.co.id'] for host in test: whodata(host)
方法2:先判断字段是否存在
通过if key in dict的方式检查字段是否存在,仅当存在时才执行打印操作:
import whois def whodata(host): res = whois.whois(host) print(res['registrar']) # 仅当'emails'存在时打印 if 'emails' in res: print(res['emails']) print(res['country']) print("---------") test = ["minecraft.net", "google.com",'mob1lebn1-co.id.co.id'] for host in test: whodata(host)
如果需要同时处理多个可能缺失的字段(比如country也可能缺失),可以把这两种方法扩展到其他字段上,避免其他潜在的KeyError。
内容的提问来源于stack exchange,提问作者TheBotHunter
相关产品推荐
相关产品推荐

