请求编写Python脚本从URL文本文件提取用户名和密码
Python脚本:从URL文本文件提取用户名和密码并保存
以下是直接可用的脚本,基于Python标准库编写,无需额外安装依赖:
import urllib.parse # 可自行修改输入输出文件路径 input_file = "urls.txt" output_file = "credentials.txt" with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile: for line in infile: line = line.strip() if not line: continue # 跳过空行 try: # 解析URL并提取查询参数 parsed_url = urllib.parse.urlparse(line) query_params = urllib.parse.parse_qs(parsed_url.query) # 获取用户名和密码(取参数列表第一个值) username = query_params.get('username', [''])[0] password = query_params.get('password', [''])[0] if username and password: outfile.write(f"{username}:{password}\n") except Exception as e: print(f"处理URL '{line}' 出错: {str(e)}") print(f"提取完成,结果已保存到 {output_file}")
关键说明
- 用Python内置的
urllib.parse处理URL解析,不用额外装包,新手直接就能用 - 自动跳过空行,遇到无效URL会打印错误提示但不中断程序运行
- 仅当用户名和密码同时存在时,才会写入输出文件
使用步骤
- 把你的URL文本保存为
urls.txt,和脚本放在同一文件夹 - 运行脚本,自动生成
credentials.txt,里面就是你要的username:password格式内容 - 如果你的输入/输出文件名不同,直接修改脚本里的
input_file和output_file变量就行
内容的提问来源于stack exchange,提问作者DKal
相关产品推荐
相关产品推荐

