BeanShell Scripting in JMeter

Before starting with beanShell scripting demo, let's first understand what is a BeanShell.
A BeanShell is light-weight scripting language. It has Java like syntax and being a scripting language it is interpreted instead of compiled.

BeanShell Scripting in JMeter example

In this example, we will open the search engine Bing, write a search term and fetch top 5 links from the search results.

Step.1. I hope you are aware of usual JMeter scripting, so we won't go in deep and assume that script to open bing and write search term is already scripted. As shown in the image below, we have a transaction controller "Launch bing" and "Get all results links". This transaction controllers will have there respective http requests.

BeanShell Scripting in JMeter

Step.2. First of all we will run the script and get text response in the view result tree and create regular expression to fetch link, for more information about regular expression extractor, please refer to out post on Correlation in JMeter.

Step.3. Next step would be to create the Regexp Extractor that will be added as child of the http request under the "Get all result links" controller.

Step.4. Add beanshell Script element as child and write the following code-

keyword = "buddha quotes";
links = vars.get("links");
f = new FileOutputStream("result.csv",true);
p = new PrintStream(f); 
print(keyword +  ","  + links);

Check the image below for reference -

BeanShell Scripting in JMeter

The code is self explanatory and will create a result.csv file with links for the keyword "buddha quotes". Also, we can parameterize the keyword and make script more generic and dynamic.