Python从URL获取邮箱并统计域名数量时出现TypeError的问题排查
问题
需求是从指定URL获取邮箱地址,统计相同域名的邮箱数量,但运行代码时出现错误:
TypeError: object of type 'Response' has no len()
错误出现在代码第10行for i in range(len(input_)):,因为传入finddomains函数的input_是requests.get()返回的Response对象,不是可迭代的邮箱列表。
错误原因
requests.get(link)返回的是Response对象,它包含HTTP响应的状态码、头部、内容等元信息,不是直接的文本内容,因此无法用len()获取长度,也不能通过下标访问元素。必须先从该对象中提取出实际的文本内容,再处理其中的邮箱地址。
修正后的代码
import requests import re def find_domains(emails): domain_freq = {} # 匹配标准邮箱格式的正则表达式 email_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}') for email in emails: # 验证并提取有效邮箱的域名 cleaned_email = email.strip() if email_pattern.fullmatch(cleaned_email): domain = cleaned_email.split('@')[1] domain_freq[domain] = domain_freq.get(domain, 0) + 1 # 按域名排序后返回结果 return sorted(domain_freq.items()) # 驱动代码 link = "your_target_url_here" try: response = requests.get(link) response.raise_for_status() # 捕获HTTP请求错误 # 将响应文本按行分割,过滤空行得到有效邮箱行 email_lines = [line for line in response.text.splitlines() if line.strip()] result = find_domains(email_lines) for domain, count in result: print(domain, count) except requests.exceptions.RequestException as e: print(f"请求失败: {e}")
修改说明
- 替换原代码中直接将Response对象传入函数的逻辑,先通过
response.text提取网页文本内容 - 添加正则表达式验证邮箱格式,避免处理无效行时抛出异常
- 用
splitlines()分割文本并过滤空行,得到有效邮箱行列表 - 用
domain_freq.get(domain, 0) + 1简化字典计数逻辑 - 新增网络请求异常处理,捕获请求失败、HTTP错误等情况
内容的提问来源于stack exchange,提问作者Kowshik Diamond
相关产品推荐
相关产品推荐

