Extracting var from script html response

I’m running into an issue with the correct JavaScript code to use and can’t figure it out.

I have a request which returns an html response
The html response contains a script tag, and inside that tag are several variables I need to access

The furthest I’ve gotten was converting the html to string but can’t seem to google correctly to find the best script to extract that

@ilyaf Welcome to the Community :partying_face:

Here is a sample collection to parse the HTML response. Please check if it’s helpful.

Also there are many posts in the forum to parse the HTML response like the above one. Try to explore, if you are not finding the solution please post the response here (if there’s no confidential data) :blush: All the best!

@bpricilla I am new in postman automation so could you please help me on it, How can we extract variable from html response.

I want to get the id of g_listData,

<html>
        <body>
        <script type="text/javascript">

        var g_deferData= "testdata";

        var g_listData = {"ListData":{ "Row" : [{
        	"ID": "85018",
        	"FileLeafRef": "test only"
        	}
        	,{
        	"ID": "85091",
        	"FileLeafRef": "completed"
        	}]
          }}
        </script>
        </body>
     </html>

Hello @sureshjsh9, Welcome to the Community :partying_face:

Usually for HTML response parsing we use Cheerio.

This HTML is different with the type “text/javascript”.

// Load the HTML response to $
const $ = cheerio.load(pm.response.text());

console.log($("script").text()); 

Using this I can reach till the script tag. Please explore using Cheerio. I will update you if I find any solution to parse this :blush:

1 Like

@ilyaf @sureshjsh9 : You can do something like this. ~

  1. Extract the string in the script tag
  2. Extracted string is a multi-line string, so iterate over it.
  3. If you have to access a particular variable which appears more than once like ID in this case you can put it in an array and access the desired variable as per your need based on the index.
  4. eventually set it in a global or an environment variable as per your usecase
const $ = cheerio.load(pm.response.text());
const scriptString = $("script").text();
const lines = scriptString.split("\n");

for (var i = 0; i < lines.length; i++ )
    {
        const tokenString = lines[i].trim();
        if (tokenString.startsWith('Token:'))
        {
            console.log(tokenString);
            pm.globals.set("findMemToken", tokenString.substring(8, 116));
        }
    }
console.log(pm.globals.get("findMemToken"));