import java.util.Random;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.apache.commons.lang.math.RandomUtils;
String responseData = prev.getResponseDataAsString();
// log.info("the response data is : " + responseData);
Pattern pattern = Pattern.compile("<option value=\"(.+?)\">(.+?)</option>");
// log.info("pattern is : " + pattern);
Matcher matcher = pattern.matcher(responseData);
// log.info("matcher is :" + matcher);
List cities = new ArrayList();
while(matcher.find())
{
log.info("the cities are : " + matcher.group(1));
String extractedCity = matcher.group(1);
log.info("the extracted city is : " + extractedCity);
cities.add(extractedCity);
}
vars.put("Depart_city", cities.get(RandomUtils.nextInt(cities.size())));
我想以随机方式选择值,但是通过使用上面的代码,值是按顺序选择的。有没有办法构建代码来使用beanshell随机选择值`
这些值是“按顺序选取”的,因为这就是正则表达式的工作方式,匹配项将由您的“代码”按出现的顺序进行评估和打印。
如果您希望匹配项以随机顺序出现,则需要在使用正则表达式解析响应数据之前“洗牌”响应数据。
使用当前的实现
Depart_city
JMeter变量将保存随机匹配,不要注意正在打印的内容,“魔术”是通过cities.get(RandomUtils.nextInt(cities.size()))
函数调用完成的。
更多提示:
使用正则表达式解析 HTML 并不是最好的主意,您可以使用 CSS Selector Extractor 实现相同的效果,配置如下:
如果您想继续编写脚本,请考虑迁移到 Groovy,因为使用 Beanshell 是某种形式的性能反模式。有关更多详细信息,请参阅 Beanshell 与 JSR223 与 Java For JMeter:完整对决 文章。