You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Whois查询失败时如何存储默认值并继续执行

Fixing PywhoisError When Querying Non-Existent Domains in Python

Got it, let's work through this problem. The core issue with your current code is that when you query a non-existent domain like hdtrcs.com, the whois.whois() function doesn't return None — it throws a PywhoisError instead. That's why your if data != None check never gets triggered, and the program crashes before handling the rest of your domain list.

Here's a fixed version of your code with proper exception handling, plus some cleanups to make it more readable:

import whois
from whois.parser import PywhoisError

domains = ['google.com', 'stackoverflow.com', 'hdtrcs.com', 'facebook.com']
results = []

for domain in domains:
    print(f"Checking {domain}...")
    try:
        # Attempt to fetch whois data for the domain
        whois_data = whois.whois(domain)
        # Handle cases where domain_name might be a list (e.g., Google returns multiple entries)
        domain_name = whois_data.get('domain_name', 'none')
        if isinstance(domain_name, list):
            domain_name = domain_name[0]
        results.append(domain_name)
    except PywhoisError:
        # If the domain doesn't exist or throws an error, add 'none' to results
        results.append('none')

print("\nFinal results:")
print(results)

Key improvements explained:

  • Targeted Exception Handling: We wrap the whois.whois() call in a try-except block that specifically catches PywhoisError. This way, when a domain fails to resolve, the program doesn't crash — it just adds 'none' to the results and moves on to the next domain.
  • Simpler Loop: Instead of manually tracking an index i, we directly iterate over the domains list. This makes the code cleaner and less likely to have off-by-one errors.
  • Robust Domain Name Extraction: Some domains (like Google's) return a list of domain names instead of a single string. We check for that case and take the first entry. Using get() also ensures we don't hit a KeyError if the 'domain_name' field is missing for any reason.

When you run this code, you'll get the exact output you expected (note: some domains return uppercase names, but you can add .lower() if you want consistent lowercase formatting):

['GOOGLE.COM', 'STACKOVERFLOW.COM', 'none', 'FACEBOOK.COM']

内容的提问来源于stack exchange,提问作者vipul-rao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:10:46