Using jmeter variables in xpath extractor

I want to iterate over a set of table rows from an html response (for example, each row contains data that I want to use in another query). To do this, I set up a variable called COUNTER, and I installed XPath Extractor with the XPath Query field set to

//table//tr[${COUNTER}]/td[0] 

However, this does not allow to obtain a result regardless of the value of COUNTER. If I replaced $ {COUNTER} with a numeric value, for example.

 //table//tr[4]/td[0] 

works as expected.

The following error indicates that this functionality should be in 2.5.1 https://issues.apache.org/bugzilla/show_bug.cgi?id=51885 , but it does not work for me in 2.5.1 or 2.6

Using variables in XPath expressions should be very useful in jmeter, but I can not find any talk about how to do this on the Internet. I am open to alternative suggestions, but regular expressions do not immediately seem to be the right solution.

+7
source share
1 answer

Try using Beanshell PostProcessor with beanshell / java code to extract all values ​​from an xml response using an xpath request.

  • Attach the Beanshell PostProcessor as a child to the sampler that returns your html response.
  • Use the following code in PostProcessor (from an external file or paste into the "Script" field) to extract and save the keys:

     import java.io.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import org.w3c.dom.*; import org.xml.sax.SAXException; import org.apache.jmeter.samplers.SampleResult; // set here your xpath expression (to extract EVERY key, not any separate one) String xpathExpr = "//table//tr/td/text()"; try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); // access result of parent sampler via "ctx" BeanShell variable SampleResult result = ctx.getPreviousResult(); InputSource is = new InputSource(new StringReader(result.getResponseDataAsString())); Document doc = builder.parse(is); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile(xpathExpr); NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); // extract all the keys in loop for (int i = 0; i < nodes.getLength(); i++) { String key = nodes.item(i).getNodeValue(); System.out.println(key); } } catch (Exception ex) { IsSuccess = false; log.error(ex.getMessage()); ex.printStackTrace(); } 


Using xpathExpr = "//table//tr/td/text()" will give you all the columns in all the rows.
To get a more specific selection, you can:

  • refine xpath request, for example //table//tr/td[1]/text() ;
  • retrieve all values ​​and then iterate over the list of results to get what you need.

Hope this helps.

+1
source

All Articles