You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python代码实现批量下载不同文件名的文件

解决批量下载并生成不同文件名的问题

原代码的问题在于只循环赋值了最后一个URL,且文件名固定。要实现批量下载,只需把爬虫调用放到循环内部,并动态生成每个文件的唯一名称。

修改后的代码示例(两种常见命名方式)

方式1:用Excel行索引命名

import pandas as pd
import sys
import logging
from asyncio import events, windows_events

def crawler(url, out_file):
    # 这里是你的爬虫逻辑
    pass

if __name__ == '__main__':
    if '--iocp' in sys.argv:
        sys.argv.remove('--iocp')
        logging.info('using iocp')
        el = windows_events.ProactorEventLoop()
        events.set_event_loop(el)
    
    # 读取Excel文件
    df = pd.read_excel('path of file')
    # 循环处理每一行的URL
    for index, row in df.iterrows():
        url = row['Row Name']
        # 用行索引生成唯一文件名,比如sitemap_0.xml、sitemap_1.xml...
        out_filename = f"sitemap_{index}.xml"
        crawler(url, out_file=out_filename)

方式2:用URL中的域名作为文件名(处理非法字符)

import pandas as pd
import sys
import logging
from asyncio import events, windows_events
from urllib.parse import urlparse

def crawler(url, out_file):
    # 这里是你的爬虫逻辑
    pass

def get_valid_filename(url):
    # 解析URL提取域名,替换系统非法字符
    parsed_url = urlparse(url)
    domain = parsed_url.netloc or parsed_url.path.split('/')[0]
    # 替换Windows/Linux禁止的文件名字符
    return f"sitemap_{domain.replace('/', '_').replace(':', '_')}.xml"

if __name__ == '__main__':
    if '--iocp' in sys.argv:
        sys.argv.remove('--iocp')
        logging.info('using iocp')
        el = windows_events.ProactorEventLoop()
        events.set_event_loop(el)
    
    df = pd.read_excel('path of file')
    for index, row in df.iterrows():
        url = row['Row Name']
        out_filename = get_valid_filename(url)
        crawler(url, out_file=out_filename)

关键修改点

  • 将crawler函数调用移入df.iterrows()循环内,确保每个URL都被单独处理
  • 动态生成out_file参数,避免文件名重复覆盖
  • 如果Excel里有专门存储文件名的列,直接用row['文件名列名']作为输出文件名即可

内容的提问来源于stack exchange,提问作者Muhammad Tayyab Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:15:42