如何在JMeter的多个JSR223 Sampler间传递WebDriver对象
在JMeter多个JSR223 Sampler间传递WebDriver实例,拆分GUI操作耗时测量
要在多个JSR223 Sampler间复用同一个WebDriver实例,只需将实例存储到JMeter的线程级变量中,后续Sampler直接读取即可。以下是具体实现步骤:
1. 第一个Sampler:初始化WebDriver并存储变量
命名该Sampler为「初始化浏览器+打开谷歌」,代码如下:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.By; // 初始化ChromeDriver io.github.bonigarcia.wdm.WebDriverManager.chromedriver().setup() ChromeOptions options = new ChromeOptions().setAcceptInsecureCerts(true) WebDriver driver = new ChromeDriver(options) def wait = new WebDriverWait(driver, Duration.ofSeconds(5)) // 将driver和wait存入线程变量,供后续Sampler调用 vars.putObject("driver", driver) vars.putObject("wait", wait) // 执行第一个操作步骤 driver.get('https://google.com/') wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//button/div[contains(string(), 'Accept all')]")))
2. 第二个Sampler:读取WebDriver并执行操作
命名为「接受Cookie+输入搜索词」,代码如下:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.By; // 从线程变量中取出driver和wait实例 WebDriver driver = vars.getObject("driver") def wait = vars.getObject("wait") // 执行第二个操作步骤 def ACCEPTALL_BUTTON = driver.findElement(By.xpath(".//button/div[contains(string(), 'Accept all')]")) ACCEPTALL_BUTTON.click() def SEARCH_TEXTBOX = driver.findElement(By.xpath("//textarea[@title ='Search']")) SEARCH_TEXTBOX.sendKeys("test") def SEARCH_BUTTON = driver.findElement(By.xpath("//div/div[4]/center//input[@value ='Google Search']")) // 如果需要复用SEARCH_BUTTON,可存入变量(可选) vars.putObject("searchButton", SEARCH_BUTTON)
3. 第三个Sampler:继续执行操作并关闭浏览器
命名为「点击搜索+等待结果+关闭浏览器」,代码如下:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.By; // 读取实例 WebDriver driver = vars.getObject("driver") def wait = vars.getObject("wait") def SEARCH_BUTTON = vars.getObject("searchButton") // 读取之前存储的按钮实例 // 执行第三个操作步骤 SEARCH_BUTTON.click() wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("result-stats"))) // 操作完成后关闭浏览器 driver.quit()
关键注意事项
- 所有JSR223 Sampler必须选择Groovy作为脚本语言,勾选「Compile script if available」以提升性能。
webdrivermanager-5.3.3-fat.jar需放置在JMeter的lib目录下,重启JMeter生效。- 使用
vars.putObject()/vars.getObject()存储对象,这是线程安全的,每个JMeter线程会维护独立的WebDriver实例。 - 务必在最后一个Sampler中调用
driver.quit(),避免残留浏览器进程。
内容的提问来源于stack exchange,提问作者JustNatural
相关产品推荐
相关产品推荐

