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

如何重构Python爬虫项目中main.py内的重复Bot实例调用代码

消除重复代码的实现方案

下面是几种不同复杂度的改造方案,可根据后续业务扩展需求选择:


方案1:遍历品牌列表批量执行

最轻量化的改造方式,将品牌抽为可遍历的列表,公共参数统一声明,循环复用相同执行逻辑:

# main.py
# 公共参数统一维护
login = "你的登录账号"
password = "你的登录密码"
# 所有需要爬取的品牌都放在这个列表中
target_brands = [A, B]

for brand in target_brands:
    bot = Bot(login, password, brand=brand, ...)
    bot.log_in()
    bot.some_methods_to_scrap()

特点:后续新增爬取品牌只需往target_brands列表追加元素即可,无需新增重复代码。


方案2:封装执行流程为独立函数

如果后续执行逻辑可能调整(比如新增爬取步骤、增加异常捕获逻辑),可以把固定流程封装为函数,复用性和可维护性更高:

# main.py
def run_scrap_task(brand, login, password, **bot_kwargs):
    bot = Bot(login, password, brand=brand, **bot_kwargs)
    # 所有执行步骤都在函数内统一管理,修改一次全量生效
    bot.log_in()
    bot.some_methods_to_scrap()

# 调用时仅需传入不同品牌参数
login = "你的登录账号"
password = "你的登录密码"
run_scrap_task(A, login, password)
run_scrap_task(B, login, password)

特点:执行逻辑收敛到单个函数,调整流程不需要改动每一处实例调用的代码。


方案3:并行爬取优化(可选)

如果多个品牌的爬取任务没有依赖关系,还可以用多线程/多进程实现并行爬取,提升执行效率,示例基于concurrent.futures实现:

# main.py
from concurrent.futures import ThreadPoolExecutor

def run_scrap_task(brand, login, password, **bot_kwargs):
    bot = Bot(login, password, brand=brand, **bot_kwargs)
    bot.log_in()
    bot.some_methods_to_scrap()

if __name__ == "__main__":
    login = "你的登录账号"
    password = "你的登录密码"
    target_brands = [A, B]
    
    # 并行执行多个品牌的爬取任务
    with ThreadPoolExecutor(max_workers=2) as executor:
        for brand in target_brands:
            executor.submit(run_scrap_task, brand, login, password)

特点:适合爬取任务量大的场景,可大幅降低总耗时。


内容的提问来源于stack exchange,提问作者suziex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:24:03