webdriver采样器获取cookie值

时间:2019-08-29 06:46:24

标签: jmeter

我想将20个不同的用户(用户名和密码组合)模拟到同一站点,因为每个用户的唯一身份验证令牌都将在cookie中创建。我想提取每个用户的cookie值并将其存储在CSV文件中。

我在Web驱动程序采样器中编写了代码,该代码可以正常工作,但是每次执行测试Cookie值时,都会将其附加在上一个文件中。

WDS.sampleResult.sampleStart()
WDS.browser.get('https://preprd.bcom3test.com/app/')
var username=WDS.vars.get('Username')
var password=WDS.vars.get('Password')
WDS.log.info(username)
WDS.log.info(password)
var ui=JavaImporter(org.openqa.selenium.support.ui) 
var wait=new ui.WebDriverWait(WDS.browser,120)
wait.until(ui.ExpectedConditions.visibilityOfElementLocated(org.openqa.selenium.By.xpath("//*[@data-autoid='lion-login']")))
var login = WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@data-autoid='lion-login']"));
login.click();
wait.until(ui.ExpectedConditions.visibilityOfElementLocated(org.openqa.selenium.By.xpath("//*[@id='userNameInput']")))
var name = WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='userNameInput']"));
name.sendKeys(username);
wait.until(ui.ExpectedConditions.visibilityOfElementLocated(org.openqa.selenium.By.xpath("//*[@id='passwordInput']")))
var pass = WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='passwordInput']"));
pass.sendKeys(password);
wait.until(ui.ExpectedConditions.visibilityOfElementLocated(org.openqa.selenium.By.xpath("//*[@id='submitButton']")))
var submit = WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='submitButton']"));
submit.click();
wait.until(ui.ExpectedConditions.visibilityOfElementLocated(org.openqa.selenium.By.xpath("//*[@id='idSIButton9']")))
var submit2 = WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='idSIButton9']"));
submit2.click();
var cookie=WDS.browser.manage().getCookieNamed('MarcelAUTH').getValue();
WDS.log.info(cookie)
var output = new java.io.File('C:/Users/sapsharm/Desktop/auth.csv')
var newline = java.lang.System.lineSeparator()
org.apache.commons.io.FileUtils.writeStringToFile(output, cookie + newline, true)
WDS.sampleResult.sampleEnd() 

预期的CSV值应仅包含新的Cookie值,而CSV文件中不应包含旧的值。

1 个答案:

答案 0 :(得分:0)

替换代码org.apache.commons.io.FileUtils.writeStringToFile(output, cookie + newline, true)

具有以下代码

org.apache.commons.io.FileUtils.writeStringToFile(output, cookie + newline,null, false)

引用API Doc

方法说明:

  

公共静态无效writeStringToFile(文件文件,字符串数据,字符集   编码,布尔值附加)会引发IOException

Writes a String to a file creating the file if it does not exist.

Parameters:
    file - the file to write
    data - the content to write to the file
    encoding - the encoding to use, null means platform default
    append - if true, then the String will be added to the end of the file rather than overwriting