JMeter Cookbook
上QQ阅读APP看书,第一时间看更新

Using CSS/jQuery Extractor

JMeter offers CSS/jQuery Extractor that allows you to extract server responses using a CSS/jQuery-like syntax. This component was introduced in JMeter 2.9 and is particularly helpful when dealing with HTML responses. CSS/jQuery-like syntax allows you to easily select HTML DOM elements that might otherwise have been difficult to write a regular expression for, for example, selecting a button with a danger class in the response (button.danger), selecting images matching a particular regular expression (img[src~=(?i)\\.(png|jpeg|gif)]), and so on. The default implementation of the CSS/jQuery implementation is JSoup ( API documentation for its selector can be found at http://jsoup.org/apidocs/org/jsoup/select/Selector.html.

How to do it…

In this recipe, we will cover how to use the CSS/jQuery Extractor component to extract information from server responses. Perform the following steps:

  1. Launch JMeter.
  2. Open the ch2_css_jquery.jmx test script located in the scripts/ch2 directory.
  3. Open the HTTP request labeled add_css_jquery_here.
  4. Add CSS/JQuery Expression Extractor by navigating to Request | Add | Post Processor | CSS/JQuery Extractor.
  5. Fill in the values as follows:
        Reference Name: post
        CSS/JQuery expression: div.entry p:matches(\w+)
        Attribute: 
        Match No. (0 for Random): 0
        Default Value: NOT_FOUND
  6. Save and run the script.
  7. Open Debug Sampler and check whether the expression matches the intended query. This is shown in the following screenshot:

How it works…

As a postprocessor component, CSS/jQuery Extractor acts on requests within its scope and applies the specified CSS or jQuery expression, extracting all matches and storing them after what we specify in JMeter's session. This can then be referred to by other requests later in the execution chain.

In our case, we extracted all the div elements that matched a paragraph.

There's more…

Because of the flexibility provided by expression syntax, this component can't be fully covered within this book, but we encourage you to read more on CSS/jQuery syntax to fully harness the power of this component.

Some good starting resources are:

Also, at the time of writing this, there is another implementation (Lagarto) syntax that is supported right out of the box by JMeter. Details can be found at http://jodd.org/doc/lagarto/index.html.

Tip

Compared to Regular Expression Extractor, CSS/jQuery Extractor is resource-intensive as it does a complete HTML parse of the document to perform its work. In cases where Regular Expression Extractor can do the work, use that instead.