Python如何支持n个加密货币输入并批量导出对应命名的文件?
多币种加密货币爬取代码修改方案
核心改动是将单币种输入改为多币种分割解析,加循环遍历每个币种独立执行爬取导出逻辑即可,CmcScraper的export方法默认会以币种代码作为CSV文件名,刚好匹配你的需求,修改后的完整代码如下:
from cryptocmd import CmcScraper # 多币种输入,用英文逗号分隔 currencies_input = input("输入币种(多个用英文逗号分隔,如ETH,ICX,ALGO):") # 分割币种,去除空白字符,过滤空值 currency_list = [cur.strip() for cur in currencies_input.split(',') if cur.strip()] date_from = input("输入开始日期(格式DD-MM-YYYY,留空则爬取全部历史):") date_to = input("输入结束日期(格式DD-MM-YYYY,留空则爬取全部历史):") # 遍历每个币种执行爬取 for currency in currency_list: print(f"正在爬取 {currency} 数据...") # 初始化爬虫 if date_from and date_to: scraper = CmcScraper(currency, date_from, date_to) else: scraper = CmcScraper(currency) # 导出CSV,默认文件名为 {币种}.csv,符合需求 scraper.export("csv") # 你需要的其他数据获取逻辑也可以放在这里 # headers, data = scraper.get_data() # json_data = scraper.get_data("json") # df = scraper.get_dataframe() print("所有币种爬取完成")
补充说明
- 输入币种时支持带空格的格式,比如输入
BTC, ETH, SOL也能正常识别 - 所有币种共用你输入的同一套时间范围,若需要每个币种单独设置时间,可以把日期输入逻辑挪到循环内部
- 若需要处理无效币种代码的报错,可以在循环内加
try-except块捕获异常,避免单个币种出错导致整个程序终止
内容的提问来源于stack exchange,提问作者xbile
相关产品推荐
相关产品推荐

