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 atry-exceptblock that specifically catchesPywhoisError. 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 thedomainslist. 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 aKeyErrorif 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
相关产品推荐
相关产品推荐

