selenium多窗口并发
时间: 2025-02-06 07:07:23 浏览: 63
### 使用 Selenium 实现多窗口并发操作
#### 创建 WebDriver 实例并启动浏览器
为了实现多窗口并发操作,首先需要创建 WebDriver 的实例。这通常涉及下载相应浏览器的驱动程序并将路径配置到环境变量中[^3]。
```python
from selenium import webdriver
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
```
#### 启动多个线程或使用 `ThreadPoolExecutor` 进行并发控制
可以利用 Python 的标准库中的 `threading.Thread` 或者更高级别的抽象——`concurrent.futures.ThreadPoolExecutor` 来管理并发任务。下面是一个简单的例子展示如何使用后者:
```python
import concurrent.futures
from selenium import webdriver
def open_browser(url):
with webdriver.Chrome() as driver:
driver.get(url)
title = driver.title
return f'Page Title is {title}'
urls = [
'https://www.google.com',
'https://www.python.org'
]
with concurrent.futures.ThreadPoolExecutor(max_workers=len(urls)) as executor:
futures = [executor.submit(open_browser, url) for url in urls]
for future in concurrent.futures.as_completed(futures):
print(future.result())
```
这段代码展示了如何在一个线程池里运行两个独立的任务,每个任务都会打开一个新的 Chrome 浏览器实例访问指定 URL,并打印网页标题[^1]。
#### 切换不同窗口句柄
当在同一浏览器内开启多个标签页时,则可以通过获取当前会话中存在的所有窗口句柄列表来进行切换。例如,在新标签页加载完成后立即保存现有窗口句柄以便稍后返回原页面继续工作[^2]。
```python
original_window = driver.current_window_handle
new_tab_script = "window.open('about:blank', '_blank');"
driver.execute_script(new_tab_script)
# 获取新的窗口句柄
windows_after = driver.window_handles
new_window = next((handle for handle in windows_after if handle != original_window), None)
if new_window:
driver.switch_to.window(new_window)
# 执行其他操作...
```
以上就是关于如何使用 Selenium 实现多窗口并发处理的方法介绍以及具体实践案例说明[^5]。
阅读全文
相关推荐

















