Python使用requests做子域名检测报MissingSchema错误如何解决?
问题排查与解决方案
报错根因
requests.exceptions.MissingSchema报错触发的直接原因是代码请求的目标URL为单个字符s,并非合法带协议的URL,该问题由文件读取逻辑错误导致:
通过argparse解析得到的args.file是传入的文件路径字符串(比如执行命令时传-f sub.txt,args.file的值就是字符串sub.txt),直接执行for line in args.file会遍历字符串的每一个字符,首个字符为s,把单个字符作为URL发起请求自然触发协议缺失报错。
其余需修复的代码问题
- 变量名拼写错误:定义的去重字典为
url = {},后续引用误写为urls[line],多了后缀s,运行时会触发NameError status_code是requests响应对象的属性而非可调用方法,代码中req.status_code()的写法会触发TypeError,需要去掉末尾括号- 异常处理缺失:已导入
MissingSchema但未实际捕获,遇到请求超时、连接拒绝、无协议子域名等情况时程序会直接中断 - 无协议子域名兼容缺失:如果子域名文件内的条目是不带http/https的纯域名(如
et7-1.fab5-2-gdc.bf1.yahoo.com),也会触发MissingSchema报错
修复后可运行代码
import argparse, requests from requests.exceptions import MissingSchema, ConnectionError, Timeout p = argparse.ArgumentParser() p.add_argument("-f", "--file", required=True, help="subdomain file path") args = p.parse_args() def get_url_nofollow(url): # 兼容无协议的子域名,自动补https前缀 if not url.startswith(('http://', 'https://')): url = f'https://{url}' try: # 不需要重定向可添加 allow_redirects=False 参数 req = requests.get(url, timeout=5, verify=False) response_code = req.status_code if response_code == 200: return response_code return None except (MissingSchema, ConnectionError, Timeout): return None def main(): url_dict = {} # 正确打开文件读取内容 with open(args.file, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue if line not in url_dict: print(f'Checking url: {line}') code = get_url_nofollow(line) url_dict[line] = {'code': code, 'count': 1} if code == 200: print(f"++ {line} 可正常访问\n") else: url_dict[line]['count'] += 1 if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者johnathan semol
相关产品推荐
相关产品推荐

