k6/html module provides functionality for parsing and manipulating HTML content in k6 scripts. It offers a jQuery-like API for selecting and extracting data from HTML responses.
Overview
Use this module to:- Parse HTML responses from HTTP requests
- Extract data using CSS selectors
- Validate HTML structure and content
- Scrape data for parameterization
Importing the Module
API Reference
Functions
Selection Class
The Selection object provides a jQuery-like API for traversing and manipulating HTML documents.Common Methods
Returns elements matching the CSS selector.Parameters:
CSS selector (e.g.,
"div.class", "#id", "a[href]")Returns the text content of the selection.Returns:
Combined text content of all matched elements
Returns the HTML content of the selection.Returns:
HTML content of the first matched element
Returns the value of an attribute.Parameters:
Attribute name (e.g.,
"href", "src", "class")Iterates over matched elements.Parameters:
Function called for each element:
(index, element) => voidReturns the element at the specified index.Parameters:
Zero-based index of the element
Traversal Methods
Returns child elements, optionally filtered by selector.
Returns parent elements, optionally filtered by selector.
Returns sibling elements, optionally filtered by selector.
Returns the next sibling element.
Returns the previous sibling element.
Returns the closest ancestor matching the selector.
Element Class
Represents a single HTML DOM element.The tag name of the element (e.g.,
"div", "a", "span")The type of the node (1 for element nodes)
The text content of the element
The HTML content of the element
Map of attribute names to values
Examples
Parsing HTTP Response
Data Extraction and Validation
Working with Tables
Form Data Extraction
CSS Selector Examples
Content Verification
Common Use Cases
Web Scraping for Test Data
Extract dynamic values from HTML to use in subsequent requests:- CSRF tokens from forms
- Session identifiers from hidden fields
- Product IDs from listings
- Dynamic URLs from navigation
HTML Structure Validation
Verify that pages contain expected elements:- Forms have required fields
- Navigation links are present
- Images have alt text
- Headers follow hierarchy
Content Verification
Validate page content matches requirements:- Check for specific text or messages
- Verify data is displayed correctly
- Ensure error messages appear when expected
- Validate dynamic content rendering
Performance Considerations
HTML parsing has overhead. For high-performance tests:
- Only parse when you need to extract data
- Use
httpresponse checks for simple validation - Cache parsed documents if parsing the same content multiple times
- Consider using
check()on response body strings for simple text matching
Related Resources
HTTP Module
Make HTTP requests
Checks
Validate responses
CSS Selectors
Learn CSS selector syntax
Data Correlation
Extract and reuse dynamic data