Hi all,
I get an HTML response from my GET request. I want to select the <div> containing {{string}} in <h2> and extract the <li> to an array. I’m using cheerio to parse html
I’ve been trying to use snippets of code from other posts and watching odanylewycz and trying out his Collection on postman. Great stuff, would recommend
Now the above will get you all text for h2 tags. So if you want to select a specific h2 tag, your selector will have to get more ‘selective’ (no pun intended)
As for the array, I just ripped this from cheerio.js intro guide. Referencing the code above…
This will set each list tag text as a value of a single array entry and then log the text of the array.
You can always can always change what you want to set into the array by doing more parsing. You can also use .html() instead of .text() if you want those tags as well.
Wow, the man himself odanylewycz .
That’s crazy, thanks so much for the reply.
I read your reply and played around with it. It worked just like you said.
After plenty of correction I managed to pull the prices using the name index. Code below;
const $ = cheerio.load(responseBody, {
ignoreWhitespace: true,
xmlMode: true
});
/* This gets all <h2> address into an array and set it in the environment as "namelist" */
var namelist = []
$('h2').each(function(i, elem) {
namelist[i] = $(this).text();
});
/* Get all the Historical Prices <li> into an array and set it to environment as "pricelist" */
var pricelist = []
$('section[class="grid-oneone"]').each(function(i, elem) {
Histprices[i] = $(this).find('li').text();
});
/* Get environment variable "name" and search [namelist] for index*/
var searchname = pm.environment.get("name");
var searchindex = searchname.indexOf(searchname);
/* If the list of names contains the specific one I'm looking for, it will return the index number. If not, it will return -1 */
console.log("Name Lookup", searchname)
console.log("Name Index", searchindex)
/* Using the name Index, we pull the prices from the [pricelist] Array using that index */
var nameprices = pricelist[searchindex]
console.log(nameprices)
/* Finish by setting the result to a environment variable */
pm.environment.set("Prices", nameprices);
Example, I scraped 20 names in <h2> from response body into the array [namelist]
Each name has several prices so I scraped the <li> for each section into the array [pricelist]
Since the index for each entry is the same, I can search for the name I want in the [namelist] array, return its index and use that to pull the prices in [pricelist] with same index.
It’s not the most efficient way to do this but I’m learning still.
Hey don’t need to have the most efficient solution right out of the gate! Get it working first, then optimize , at least thats the way I think about it.
Truly glad I could help, and thanks again for your kind words.