Search code examples
javascriptload-testingk6

k6 Load Testing - How extract value from HTML response


I am using the k6 Load Testing Tool for the first time.

I send a GET request and html is sent in the response. I then need to extract some values from this html.

What is the best way of doing this in HTML? I have seen in the documentation that there are the following 3 commands that could possibly be of help:

Response.body
Selection.find(selector)
Response.json([selector])

The HTML is shown below. I want to extract the values of csrf and transId

<html lang="en">

<head>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <script data-container="true" nonce="ekqlmSlKlpMlCSDxgP6erg==">
        
        var SETTINGS = {

         "csrf": "I NEED THIS VALUE",
         "transId": "I ALSO NEED THIS VALUE",
        };

    </script>
    
</head>

<body>
</body>

</html>

I think I could do it using Response.body and then searching for a substring. Is this the best way of doing it?


Solution

  • Firstly, to get the contents of the script tag, you can do

      const doc = parseHTML(res.body);
    
      const script = doc.find('head script');
      const scriptContent = script.text();
    

    Now to extract needed values from

      var SETTINGS = {
    
         "csrf": "I NEED THIS VALUE",
         "transId": "I ALSO NEED THIS VALUE",
        };
    

    you will have to do some string manipulation that is not recommended for a load test script. But you could

    a.substr(28, 15)
    

    to get csrf value and

    a.substr(57, 22)
    

    to get transId value.