合并文件夹下所有 XML 并提取链接

用 Python 正则批量读取目录下所有 XML,提取含 /downloads/ 的链接并去重写入 txt,适合快速整理站点地图和下载清单。

前言

output_file:指定存储结果的文件名和路径。 xml_directory:指定要读取的所有 XML 文件所在的目录。 download_links:创建一个空列表来存储所有找到的链接。 file_path:构建完整的文件路径。 content:读取文件内容。 links_found:使用正则表达式从文件内容中提取所有包含 ‘/downloads/’ 的链接。

合并所有xml并保存至txt

import os
import re

# 指定存储结果的文件名和路径
output_file = 'download_links.txt'

# 检查要读取的所有 XML 文件所在的目录
xml_directory = r'C:\Users\26370\Desktop\新建文件夹'

# 创建一个空列表来存储所有找到的链接
download_links = []

# 遍历指定目录下的所有文件
for filename in os.listdir(xml_directory):
    if filename.endswith('.xml'):
        # 构建完整的文件路径
        file_path = os.path.join(xml_directory, filename)

        # 打开文件并读取内容
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()

            # 使用正则表达式从文件内容中提取所有包含 '/downloads/' 的链接
            links_found = re.findall(r'<loc>https?://[^\s]+/downloads/[^\s]+/</loc>', content)
            # links_found = links_found.content.findall(r'<loc>(.*?)</loc>', content)
            # 将找到的链接添加到 download_links 列表中
            download_links.extend(links_found)

# 去除重复的链接(可选)
download_links = list(set(download_links))

# 将所有链接写入到输出文件中
with open(output_file, 'w', encoding='utf-8') as output:
    for link in download_links:
        # 清理链接,去除可能包含的 XML 标签
        cleaned_link = re.sub(r'<[^>]+>', '', link)
        output.write(cleaned_link + '\n')

print(f"共找到 {len(download_links)} 个包含 '/downloads/' 的链接,已保存到文件:{output_file}")

评论