Extract a value from a HTML response with Cheerio using Postman - html

I'm trying to get a value from request, that returns a HTML response, using Postman. I'm using Cheerio inside the script section.
The response looks like this:
<table class="etlsessions-table" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th class="someclass1">
<div>
<span>info1</span>
</div>
</th>
<th class="someclass2">
<div>
<span>info2</span>
</div>
</th>
<th class="someclass3">
<div>
<span>info3</span>
</div>
</th>
<th class="someclass2">
<div>
<span>info4</span>
</div>
</th>
</tr>
</thead>
<tbody>
<tr class="someclass5">
<td class="someclass">
<nobr>info5</nobr>
</td>
<td class="someclass6">
<nobr>info6</nobr>
</td>
<td class="someclass3">info7</td>
<td class="someclass7">
someurl1
</td>
</tr>
</tbody>
</table>
How I can get the info6 value from the someclass6 class?

As Cheerio is built-in to the Postman sandbox environment, you can use it to get the value of the element.
I'm not sure of your complete use-case but you could add something basic like this to the Tests script and print the value to the console:
const $ = cheerio.load(pm.response.text()),
elementValue = $('.someclass6 nobr').text();
console.log(elementValue)

To emphasis Danny was saying
Use the jQuery selector API to get different elements on the page reading dom
const $ = cheerio.load(pm.response.text());
console.log $('.someclass6 nobr').text(); //derive any element from class
which has value someclass6
Or you can write it like this
console.log($("td[class$='someclass6'] nobr").text()); //derive any text value within the td tag from the class which has the value someclass6
console.log($("td").attr('class')) //to fetch values from the attribute(s) of tag td
To store it as a collection variable in postman for useage in other api calls
const $ = cheerio.load(pm.response.text());
var storesomeclass6 = $('.someclass6 nobr').text();
pm.collectionVariables.set("someclass6", storesomeclass6 );

Postman is a software that will allow you to make calls to API endpoints, so basically your program will be written in node.js and you will call the endpoint with postman.
In this case and using cheerio, the code will look like something like this :
function getResponse() {
return fetch(`${YOUR API END POINT URL}`)
.then(response => response.text())
.then(body => {
const $ = cheerio.load(body);
const $info6= $('.someclass6 td );
const info6= $info6.first().contents().filter(function() {
return this.type === 'text';
}).text().trim();
const response= {
info6,
};
return response;
});
}
Best of luck !

Related

GEt element By id angular 7

hello I need to retrieve the values entered by a form after the post method so I inserted at the service level this code :
list:Client[];
constructor(private http:HttpClient) { }
postClient(formData:Client){
return this.http.post(this.rootURL+'/Clients/',formData);
}
putClient(formData:Client){
return this.http.put(this.rootURL+'/Clients/'+formData.Engagement,formData);
}
getClient(formData:Client){
return this.http.get(this.rootURL+'/Clients/GetClientByName/'+formData.Engagement);
}
and at the component level like this :
getClient(form:NgForm){
this.clientservice.getClient(form.value).subscribe(
res =>{this.client = res as Client}
)
}
and in the HTML code this:
<table class="table table-hover">
<tr>
<th class="tname">Client</th>
<th class="tname">Enagement</th>
<th class="tname">ERP</th>
</tr>
<tr *ngFor="let clt of client">
<td >{{clt.Clientname}}</td>
<td >{{clt.Engagement}}</td>
<td >{{clt.ERP}}</td>
and I can’t get the values by ID with the get I don’t know what is the problem I have neither result or error message
I think your http service(this.rootURL+'/Clients/GetClientByName/) return Client[] not Client.
So, You should cast like this.
this.clientservice.getClient(form.value).subscribe(
res =>{this.client = res as Client[]}
)
But, your response is fixed
{"Engagement":"56789","Clientname":"ClLIENT","ERP":"ERP"}
at component level, no need to edit
getClient(form:NgForm){
this.clientservice.getClient(form.value).subscribe(
res =>{this.client = res as Client}
)
}
you should edit html file.
<table class="table table-hover">
<tr>
<th class="tname">Client</th>
<th class="tname">Enagement</th>
<th class="tname">ERP</th>
</tr>
<tr>
<td >{{client.Clientname}}</td>
<td >{{client.Engagement}}</td>
<td >{{client.ERP}}</td>
</tr>
---------------------------
or need to use ngFor loop, edit component level. and no need to edit component level.
client: Client[] = [];
getClient(form:NgForm){
this.clientservice.getClient(form.value).subscribe(
res =>{
const cli = res as Client;
this.client.length = 0;
Array.prototype.push.apply(this.client, cli)
}
)
}

Transferring variables across HTML pages

I am taking in an input from a text box in one HTML page and saving it to local storage using this function.
function writeMail(emailInput){
console.log(emailInput);
localStorage.setItem('emailInput',emailInput);
let theEmail = localStorage.getItem('emailInput');
console.log(theEmail);
}
This works fine and I can check the inputs are correct through my console logs.
Yet when I try and get this from local storage to store in my table in my emailList html file, it seems to not work at all.
<body>
email = localstorage["emailInput"];
<table>
<caption> Email list
</caption>
<tr>
<th> Name </th>
<th> Email </th>
</tr>
<tr>
<td>email </td>
</tr>
</table>
</body>
For you to be able to manipulate the contents of HTML, you need to modify the DOM node specifically. In this specific case you should have an id attribute on the <td>and then use the innerHTML property of that node to set the desired value.
i.e.:
<td id="xpto"></td>
then on the code:
let theEmail = localStorage.getItem('emailInput');
document.getElementById("xpto").innerHTML = theEmail;
You should also set that code inside of a function that is called once the document has finished loading, so something like:
JAVASCRIPT:
function go(){
let theEmail = localStorage.getItem('emailInput');
document.getElementById("xpto").innerHTML = theEmail;
}
HTML:
<body onload="go()">

Bind first value and remove all other repeating value from a ng-repeat

I have a scenario to bind a html table using angular js. In my table i need to show an a tag based on another column value(Payment Status). If its fully paid no need to show the a tag, else need to show it for very next element. I am a new one in angular.
<table>
<thead>
<tr>
<th>Month</th>
<th>Installement</th>
<th>PaymentAmount</th>
<th>PaymentDate</th>
<th>Payment Status</th>
<th>Pay</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="row in rowCollection|orderBy:type:reverse|filter:searchKeyword|itemsPerPage:maxsize">
<td>{{row.Month}}</td>
<td>{{row.MonthlyInstallement}}</td>
<td>{{row.PaymentAmount}}</td>
<td>{{row.PaymentDate}}</td>
<td>{{row.PaymentStatus}}</td>
<td ng-if="row.PaymentStatus == 'UNPAID'">
Pay Online
</td>
<td ng-if="row.PaymentStatus == 'FULLY_PAID'">
</td>
</tr>
</tbody>
</table>
function bindFinanceDetails() {
var finUrl = baseurl + 'api/FinancialStatement/GetCarFinanceInfo';
var req = {
method: 'post',
data: {
LoginID: LoginID,
ContractNumber: 11170200669,
CustomerId: 2355898046
},
url: finUrl,
headers: {
RequestedPlatform: "Web",
RequestedLanguage: cookiePreferredLanguage,
Logintoken: $cookieStore.get('LoginToken'),
LoginId: LoginID
}
};
$http(req).then(function(response) {
var getData = response.data.FinanceList;
$scope.rowCollection = getData;
}, function(error) {
toastr.error($filter('translate')('Error Occured'));
});
}
A quite hacky solution will be something like the following (just showing you the needed change in the unpaid td element):
<td ng-if="row.PaymentStatus === 'UNPAID'" ng-show="$index === data.payOnlineIndex"
ng-init="data.payOnlineIndex = (!data.payOnlineIndex || (data.payOnlineIndex > $index)) ? $index : data.payOnlineIndex">
Pay Online
</td>
This way ng-init will run for all unpaid elements, setting the smallest index to the payOnlineIndex variable. ng-show will make sure to only show that one element that has the smallest index.
I encapsulate payOnlineIndex with a data object to keep a stable reference to it. This also requires the following addition to the controller code:
$scope.data = { payOnlineIndex: null };
See a working jsFiddle example here: https://jsfiddle.net/t3vktv0r/
Another option is running your filter and orderBy in the controller, searching for the first occurrence of an "unpaid" row, and marking that element for the "pay online" feature with some flag you can test with ng-if in your view.

send data from two models of Mongoose inside Express.js to display in view list data

I have a Shopping Website I want to be able to display two model names "jeans" and "shirt" in a view
I need to pass data from two models I know how to access data from two models in one controller but I do not know how to send data from that controller
Controller:
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Shirt = mongoose.model('Shirt'),
Jeans = mongoose.model('Jeans');
exports.list = function(req, res) {
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
Ajean = jeans;
});
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
Ashirt = shirts;
});
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(all) {
// res.jsonp(Ashirt);
// res.jsonp(Ajean);
});
};
View:
<div class="list-group">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="item in items">
<td data-ng-bind="item.name"></td>
<td data-ng-bind="item.color"></td>
</tr>
</tbody>
</table>
</div>
I know that I cannot use "res.jsonp();" more than once .
when I use "Ajean" it give me data for "jeans" and
when I use "Ashirt" it give me data from "shirts" model
But I want to be able to show both data from both "shirt" model and "jean" model
How Can I do That?
Do I need to merge two Json?
How should I change my view to see that data?
Thanks!
You could try nesting the queries and then merge the resulting arrays with Array.concat:
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
var all = shirts.concat(jeans);
res.jsonp(all);
});
});

parse html within ng-repeat

I've been searching for hours now and I can't seem to find how to parse HTML code when retrieving using ng-repeat. I checked out $sce.trustAsHtml but I don't know how to apply it in my code.
html file:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<h2>My Links</h2>
<table class="table table-bordered">
<thead>
<tr>
<td>Name</td>
<td>URL</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="stuff in myStuff()">
<td>{{stuff.name}}</td>
<td>{{stuff.url}}</td>
</tr>
</tbody>
</table>
</div>
javascript
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.myStuff = function() {
return [
{
'name':'Google',
'url':'Google'
},
{
'name':'Yahoo',
'url':'Yahoo'
},
{
'name':'Microsoft',
'url':'Microsoft'
}
];
};
});
It's displaying the HTML source but I want it compile the code. Is my JS approach wrong? I'll be applying it to a json file using $http directive once I figure this out. Can anyone shed some light? I have my code at http://jsfiddle.net/s2ykvy8n/
Thanks.
Include ng-sanitize script and in your module add dependency.
var myApp = angular.module('myApp', ['ngSanitize']);
and just use ng-bind-html
<td ng-bind-html="stuff.url"></td>
and you are good to go:-
Plnkr
With what you are doing, the html in the binding will be displayed as textcontent in the element while processed by interpolation directive.
My first inclination (since from your example, you are just returning links) is to advise you to remove the html from your returned json and just return the url as a string.
Format:
{
'name': 'Google',
'url': 'http://google.com'
}
Then your HTML looks like this,
<tbody>
<tr ng-repeat="stuff in myStuff()">
<td>{{stuff.name}}</td>
<td>{{stuff.name}}</td>
</tr>
</tbody>
But, if you MUST have HTML strings in your json file, I would take a look at $compile. There are examples towards the bottom that can help you on how you can create a directive to compile your 'url' string to HTML