import requests import xml.etree.ElementTree as ET import os def get_channel_ids(url): print(f"正在获取数据: {url} ...") try: # 1. 发送请求获取 XML 内容 response = requests.get(url, timeout=30) response.raise_for_status() # 2. 解析 XML root = ET.fromstring(response.content) # 3. 提取并去重 unique_ids = [] seen = set() for channel in root.findall('channel'): channel_id = channel.get('id') if channel_id and channel_id not in seen: seen.add(channel_id) unique_ids.append(channel_id) return unique_ids except requests.exceptions.RequestException as e: print(f"网络请求错误: {e}") return [] except ET.ParseError as e: print(f"XML 解析错误: {e}") return [] if __name__ == "__main__": target_url = "http://live.fanmingming.cn/e.xml" output_file = "epglist.txt" ids = get_channel_ids(target_url) if ids: # 生成逗号分隔的字符串 result_string = ",".join(ids) # 写入文件 try: with open(output_file, "w", encoding="utf-8") as f: f.write(result_string) print(f"\n成功! 已将 {len(ids)} 个频道 ID 保存到: {output_file}") # 也可以选择在控制台打印前几个看看 print(f"预览前5个: {result_string[:50]}...") except IOError as e: print(f"写入文件失败: {e}") else: print("未提取到任何数据,未生成文件。")