I’m using the package Cheerio to webscrape from a website (https://www.realmeye.com/items/misc). However, they have made this awkward and I don’t know how to get the values. How would I get the “data alternatives” and then format them so it only says the Server Names.
Here is my code and the website source:
request(options, function(err, resp, html) {
if (!err) {
const $ = cheerio.load(html);
console.log(html);
$('span', '#i3180').each(function() {
var url = $(this).text();
urls.push(url);
})
}
<td><span class="item" data-item="3180" id="i3180"></span></td>
<td></td>
<td><span class="cheapest-server" data-alternatives="[["USWest2 Nexus",100,67,26],["USWest Nexus",100,76,25],["USMidWest2 Nexus",100,71,25],["USSouth2 Nexus",100,50,25],["USWest3 Nexus",100,88,24],["EUSouthWest Nexus",100,70,24],["USMidWest Nexus",100,50,24],["USEast3 Nexus",100,92,16],["EUSouth Nexus",100,63,12],["USNorthWest Nexus",100,60,12],["EUNorth2 Nexus",100,88,11],["EUWest2 Nexus",100,72,9],["USSouthWest Nexus",100,54,9],["USSouth Nexus",100,52,9],["USSouth3 Nexus",100,93,7],["USEast2 Nexus",100,61,3],["AsiaSouthEast Nexus",100,99,0],["USEast Nexus",100,67,0]]">Australia Nexus</span></td>
In Cheerio, you get access to an element's attribute with the attr method:
$('selector').attr('attribute')
The data in data-alternatives is a JSON, so all you need to do is to parse it, but before, replace the " with "
The complete solution would look like this:
let servers = $('.cheapest-server').attr('data-alternatives')
let parsedServers = JSON.parse(servers.replace(/"/g,'"');
There are two options for getting data attributes
Option 1
$('.cheapest-server').attr('data-alternatives')
Option 2
$('.cheapest-server').data('alternatives')
Documentation:
https://cheerio.js.org doesn't have section links but on the frontpage they have two headlines named
.attr( name, value )
.data( name, value )
They refer to the jQuery docs for more examples
https://api.jquery.com/attr/
https://api.jquery.com/data/
Side note: In plain JS you'd write
option 1: document.querySelector(".cheapest-server").attr("data-alternatives")
option 2: document.querySelector(".cheapest-server").dataset.alternatives
Related
Since I want to get the companyTitle when a user selects something from the dropdown menu. I have defined it like this data-description="${companyTitle}" as shown in the code below of the success function of my Ajax call.
success : function(data) {
$.each(data.personnelData.reverse(), function (i) {
let companyId = data.personnelData[i].companyId;
let companyTitle = data.personnelData[i].title;
let dateOfCreation = moment(data.personnelData[i].createDate).format('MM/DD/YYYY');
$("#myList").append(`<option data-description="${companyTitle}" value="${companyId}">${companyTitle}|${dateOfCreation}</option>`);
});
},
When I tested it like this in my javascript code:
$("select#myList").change(function(){
console.log("Testing companyTitle");
console.log($('#myList :selected').data('description'));
})
I only saw the following in the console log - Company Set for
And I believe it is because of the following:
When I inspected the option tag in the browser, It showed me the following entry:
<option data-description="Company Set for " abc="" pxy="" psqrty#12:20:49"="" (4="" companies="" on="" 09="" 22="" 2020="" 01:20:53="" pm)"="" value="12345">Company Set for "Abc Pxy Psqrty#12:20:49" (4 companies on 09/22/2020 01:20:53 PM)|09/22/2020</option>
How can I fix this so that inside $("select#myList").change(function(){ I can retrieve only the part inside the double quotes (i.e. Abc Pxy Psqrty#12:20:49) of the following companyTitle:
Company Set for "Abc Pxy Psqrty#12:20:49" (4 companies on 09/22/2020 01:20:53 PM)
If rather than building your option using string concatenation, you build it using jQuery's object model the description data does not get garbled because of the quotes:
const companyTitle = "Company Set for \"Abc Pxy Psqrty#12:20:49\" (4 companies on 09/22/2020 01:20:53 PM)",
companyId = 1,
dateOfCreation = "01/01/2020";
const $option = $('<option />')
.val(companyId)
.text(`${companyTitle}|${dateOfCreation}`)
.data('description',companyTitle);
$('#myList').append($option);
$('#myList').on('change', function(){
console.log($(":selected", this).data('description'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myList">
<option>Select</option>
</select>
If you then want to extract just the bit in quotes that should be fairly straightforward - use regex or string manipulation. There are plenty of examples of extracting the value between quotes.
When data in the data.personnelData[i].title always similar and has only one pair of double quotes you can split that string like:
var companyTitle = "Company Set for \"Abc Pxy Psqrty#12:20:49\" (4 companies on 09/22/2020 01:20:53 PM)";
var companyTitleDescription = companyTitle.indexOf('"') > -1 ? companyTitle.split("\"")[1] : companyTitle;
console.log(companyTitleDescription);
and assign that to your data-description attribute.
Im working on project which need to assign a value in array from json to particular ID on multiple table in and .
As you see below the html that contains ID in title and odds. And you can see i was writing dead for this particular html therefore i need to retrieve from backend which the particular title and odds will be change based on the backend given value.
HTML
<tr><th class="GB1_0 name" id="t_B1_0" title="第一球 0"><input type="hidden" id="k_B1_0" value="BALL"><span class="b0">0</span></th>
<td class="GB1_0 odds" id="o_B1_0">9.93</td>
<td class="GB1_0 amount ha"><input name="B1_0" class="ba"></td>
</tr>
List of array with jSON :
How do we do this ? Kindly advice Thanks you
Is this what you are looking for?
<script>
$( document ).ready(function() {
var jsonObj = {
B1_0 : 9.93,
B1_1 : 9.95,
B1_2 : 9.94
};
$.each(jsonObj, function (index, value) {
console.log(index);
console.log(value);
$("#o_"+index).html(value);
});
});
</script>
For My projet i need to know how i can transmit some variables to a async url. The plugin I use is a simple popover that call a URL to fetch html data and show the result.
I need to use $(this) because i have many URls with the same class. I must transmit the data-type (ex: picture) and the id of the product (data-id).
My link = Check this out
What i want to do (but it doesn't work) :
$('.product').webuiPopover({
var productType = $(this).data('type');
var id = $(this).data('id');
type:'async',
url:'/api/popover/'+ productType +'/'+id
});
Is it possible ? How i can do that ?
Note : here is the plugin I use (github : sandywalker/webui-popover)
You have to initialize webuiPopover for each .product element individually. Do something like this:
$('div').each(function(index, el){
$(el).webuiPopover({
title: $(el).data('foo') // Direct access to the data attributes of this element
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.webui-popover/1.2.5/jquery.webui-popover.min.js"></script>
<div data-foo="First title">Hello</div>
<div data-foo="Second title">Goodbye</div>
If you want to add variable then you can do it like:
$('.product').each(function(i,t){
var t = $(t);
t.webuiPopover({
type:'async',
url:'/api/popover/'+ t.data('type') +'/'+ t.data('id')
});
});
I have created a dynamic table. DEMO to my project.
I have placed this dynamic table in the form under a div named 'box'
<div id="box">
</div>.
I am creating dynamic hidden variables table using Jquery which I need to store in DB. This is how I am creating the hash to submit to server.
criteria = $('form_name').serialize(true);
criteria = Object.toJSON(criteria);
// Build the object to store the parameters for the AJAX post request
parameters = {
title : $('report_title').value,
description : $('report_description').value,
criteria : criteria
}
// Make the AJAX post request
new Ajax.Request( URL, {
method: 'post',
parameters: parameters,
onSuccess: function( response ) {
$('messageSpan').innerHTML = response.responseText;
$('spinner').style.display='none';
}
});
I am not able to capture the dynamically created values in the criteria.
How to solve this?
In the dynamically created section, I tried adding a submit button and see if the values can be fetched. I am able to fetch and iterate all the hidden variables.
$('#jquerysaveButton').click(function(){
jsonObj = [];
$("input[id=rubric_cell]").each(function () {
var id = "cell_" + row + "_" + col;
item = {}
item["id"] = id;
item["selected_rubric"] = $(this).val();
jsonObj.push(item);
});
console.log(jsonObj); //I am getting the required values here
});
How to get these values in the criteria = $('form_name').serialize(true);. Am I doing some thing wrong? Please help me. thanks in advance.
DEMO to my project
You need to make sure that your hidden input fields have a name attribute set otherwise $.serialize will not process them.
I'm using chap links library https://github.com/almende/chap-links-library/tree/master/js/src/network for drawing an area of objects.
I want to be able to use the id that I have set to an object upon click, I have this code
function onselect() {
var sel = network.getSelection();
console.log("selected "+sel[0].row);
}
It works fine, only it retrieves the row number from the dynamically created table. I want to retrieve a value from that row (an object id that I set) but I don't know how to access it.
I have tired things like
sel[0].row.id
sel[0].row.getId()
sel[0].row[0]
But I don't know how they structure the data in their thing...
Anyonw run into this before and solved it?
This is the way I set the data
nodesTable.addRow([45, "myObjectName", "image", "images/container_icons/icon.png"]);
For my app I solved it by creating a parallel array...
//rendera objekt
window.clickHelper = []; //keep track of container id in conjunction with hierarchy-canvas-object's id
var i = 0; //counter for above
Populating it upon every node creation...
nodesTable.addRow([{{ c.id }}, "{{ c.name }}", "image", "{{ asset('images/container_icons/'~c.icon~'.png') }}"]);
clickHelper[i]={{c.id}};
i++;
Then calling in data from that array on my onSelect event...
function onselect() {
//get selected node from network
var sel = network.getSelection();
sel = sel[0].row;
//get path base structure
var path = '{{ path('editGroup') }}';
//fix path with the DB id of the clicked object
path = path+clickHelper[sel];
window.location.href = path;
}
The double {{ }} are TWIG templating for those unfamiliar with that. Mixed javascript and TWIG ServerSide code here, sorry.