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())));
i want to pick value in a random way but by using the above code the values are picked in sequence way.is there a way to build code to pick a value randomly using beanshell`
The values are "picked in sequence" because this is how regular expressions work, the matches are evaluated and printed by your "code" in order of appearance.
If you want matches to appear in random order you need to "shuffle" the response data before parsing it with regular expressions.
With the current implementation Depart_city
JMeter Variable will hold the random match, don't pay attention to what is being printed, the "magic" is done by cities.get(RandomUtils.nextInt(cities.size()))
function call.
Couple more hints:
Using regular expressions for parsing HTML is not the best idea, you can achieve the same using CSS Selector Extractor configured like:
If you want to continue with scripting consider migrating to Groovy as using Beanshell is some form of a performance anti-pattern. See Beanshell vs. JSR223 vs. Java For JMeter: Complete Showdown article for more details.