Python实现多Chrome浏览器并行打开不同URL的问题求助
问题分析
原代码存在几个关键问题导致无法正常运行:
open_browser_with_url作为类方法,既没有self参数也未声明为静态方法,实例调用时会出现参数不匹配错误。- 使用
yield将方法变成生成器,ThreadPoolExecutor.map不会迭代生成器,导致后续的等待和退出逻辑完全不会执行。 - 隐式等待的位置不合理,且浏览器打开后直接退出的逻辑不符合“并行运行”的需求(若需保持浏览器打开,需调整退出时机)。
修正后的代码
方案1:使用普通函数(更简洁)
import concurrent.futures from webdriver_manager.chrome import ChromeDriverManager from selenium import webdriver import time url_list = ["https://www.example.com", "https://www.google.com", "https://www.openai.com"] def open_browser_with_url(url): # 初始化Chrome驱动 driver = webdriver.Chrome(executable_path=ChromeDriverManager().install()) # 设置全局隐式等待 driver.implicitly_wait(10) # 打开目标URL driver.get(url) # 延迟10秒(模拟业务操作,可根据需求调整或移除) time.sleep(10) # 如需自动关闭浏览器则保留该行,否则注释掉 driver.quit() if __name__ == "__main__": num_parallel_sessions = len(url_list) with concurrent.futures.ThreadPoolExecutor(max_workers=num_parallel_sessions) as executor: executor.map(open_browser_with_url, url_list)
方案2:使用类的静态方法
import concurrent.futures from webdriver_manager.chrome import ChromeDriverManager from selenium import webdriver import time url_list = ["https://www.example.com", "https://www.google.com", "https://www.openai.com"] class Test_concurrent: @staticmethod def open_browser_with_url(url): driver = webdriver.Chrome(executable_path=ChromeDriverManager().install()) driver.implicitly_wait(10) driver.get(url) time.sleep(10) driver.quit() @staticmethod def test_perform_actions(): num_parallel_sessions = len(url_list) with concurrent.futures.ThreadPoolExecutor(max_workers=num_parallel_sessions) as executor: executor.map(Test_concurrent.open_browser_with_url, url_list) if __name__ == "__main__": Test_concurrent.test_perform_actions()
关键说明
- 新增
time.sleep(10)是为了让浏览器保持打开状态以便观察效果,实际业务中可替换为具体的页面操作逻辑。 - 若不需要自动关闭浏览器,直接注释掉
driver.quit()即可。 - 使用
@staticmethod修饰类方法后,无需实例化类即可直接调用,避免了参数传递错误。
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

