How to retrieve attribute of element in CasperJS using an XPath expression - javascript

I have a webpage with this between lines:
<a href="http://foo.com/home.do?SID=3443132">...
I need to extract "href" attribute using XPath. In the API of CasperJS is wrote this information about this: clientutils.getElementByXPath.
Here is my code:
phantom.casperPath = '..n1k0-casperjs-5428865';
phantom.injectJs(phantom.casperPath + '\\bin\\bootstrap.js');
var casper = require('casper').create();
var url = "...";
casper.start(url, function() {
casper.echo("started");
});
var x = require('casper').selectXPath;
casper.then(function()
{
casper.echo("getsid");
this.test.assertExists(x('//a[contains(#href, "home.do?SID=")]'), 'the element exists');
var element = __utils__.getElementByXPath('//a[contains(#href, "home.do?SID=")]');
});
But it fails. it returns this:
false
undefined
started
getsid
PASS the element exists <== XPATH WORKS
FAIL ReferenceError: Can't find variable: __utils__
# type: uncaughtError
# error: "ReferenceError: Can't find variable: __utils__"
ReferenceError: Can't find variable: __utils__

Try this:
phantom.casperPath = '..n1k0-casperjs-5428865';
phantom.injectJs(phantom.casperPath + '\\bin\\bootstrap.js');
var url = "...";
var casper = require('casper').create();
var x = require('casper').selectXPath;
casper.start(url, function() {
casper.echo("started");
});
casper.then(function() {
casper.echo("getsid");
var xpath = '//a[contains(#href, "home.do?SID=")]';
var xpath_arr = { type: 'xpath', path: xpath};
this.test.assertExists(xpath_arr, 'the element exists');
var element = x(xpath);
});

As pointed out in the comments, you would have to use __utils__ inside the evaluate callback, because it is injected into the page. Since you want(ed) the href, you could use:
casper.then(function(){
casper.echo("getsid");
this.test.assertExists(x('//a[contains(#href, "home.do?SID=")]'), 'the element exists');
var href = this.evaluate(function(){
var element = __utils__.getElementByXPath('//a[contains(#href, "home.do?SID=")]');
return element.href;
});
});
This can be shortened with the usage of casper.getElementAttribute:
casper.then(function(){
casper.echo("getsid");
this.test.assertExists(x('//a[contains(#href, "home.do?SID=")]'), 'the element exists');
var href = this.getElementAttribute(x('//a[contains(#href, "home.do?SID=")]'), "href");
});
You can also use casper.getElementInfo to get the complete info of the element including all the attributes (but only some properties).

Related

Removing \&quote; from the beginning of an url

I want to remove "&quote; from the beginning of an url like for instance when a url has something like this href=""https://www.google.com" how do i get rid of the &quote; from the beginning of the url using javascript.
I tried something like this,
$(document).ready(function(){
$('a[href^="\"https://"]').each(function(){
var oldUrl = $(this).attr("href"); // Get current url
var newUrl = oldUrl.replace("\"https://", "https://"); // Create new url
$(this).attr("href", newUrl); // Set herf value
});
});
Google
Gmail
The working code :
$(document).ready(function(){
$("a").each(function() {
//console.log($(this).attr("href"));
var oldUrl = $(this).attr("href"); // Get current url
var newUrl = oldUrl.replace('\\"', ' ');
//console.log($(this).attr("href").replace('\\"', ' '));
$(this).attr("href", newUrl); // Set herf value
});
});

Cannot read property toLowerCase of undefined

So, I am working on an audio part where I fetch my words from a JSON file and when I show them on my front-end it should onclick on the audio button fetch the word from the server and create the audio... But I keep on getting Cannot read property toLowerCase of undefined and I cannot seem to find the error.
let's start with the variables I declared:
var MEDIAARRAY;
var WORDS;
var audioArray;
var audio = new Audio();
var LANGUAGE;
var SOUNDARRAY;
The piece of code (I took over the code given as answer and it helped me a bit further so I decided to edit the question with the code I have right now).
$(document).ready(function () {
getFileArray();
});
$(document).on("click", ".sound", function () {
getFileArray("SomeLanguage");
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
var currentVal = $(this).parent().find('.fa-volume-up');
if (foundID > -1) {
var audio = new Audio();
audio.src = 'TheServerURL' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[foundID] + '';
audio.play();
}
});
The line where the error occurs:
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
The button where the class sound is appended to:
function getAudioForWords() {
var audioBtn = $('<a/>', {
'class': 'sound btn btn-primary'
}).html('<i class="fa fa-volume-up"></i>');
return audioBtn;
}
the code where class exerciseWord gets append to:
var wordCol = $('<div>', {
class: 'col-md-9 ExerciseWordFontSize exerciseWord',
'id': 'wordInput[' + ID123 + ']',
text: exercise.word
});
and the piece of code that gets the fileArray, but most likely will be useless for you to inspect, but it was related to my code so... yeah.
function getFileArray(param)
{
var request = {
language: param
};
$.ajax(
{
url: "TheServerURL",
type: "POST",
async: true,
data: request,
dataType: 'json',
}).done(function (response)
{
console.log(response)
MEDIAARRAY = response;
audioArray = response.audio;
console.log(audioArray);
});
}
The error states varialble MEDIAARRAY remains uninitialized somewhere in your code flow. See if following takes you close to the resolution
You have not mentioned at what point getFileArray function is called. Call to getFileArray function is critical because that is when MEDIAARRAY is assigned value.
Ensure getFileArray is called before you access any propery of MEDIAARRAY.
Ensure your API always returns object which contains audio property.
Example,
$(document).on("click", ".sound", function () {
//Ensure you supply parameter value to your function(i.e. value of the element you take user input from)
getFileArray("SomeLanguage");
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
var currentVal = $(this).parent().find('.fa-volume-up');
if (foundID > -1) {
var audio = new Audio();
audio.src = 'TheServerURL' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[foundID] + '';
audio.play();
}
});

Parsing URL in Javascript

I have 2 URL like this:
http://localhost/gtwhero/public/users/3/subscribers-lists/1/subscribers
http://localhost/gtwhero/public/users/3/subscribers-lists/
So, URL format is like it:
{baseURL} +"users/{user_id}/subscribers-lists/"+{id}+"/subscribers"
Or-
{baseURL} +"users/{user_id}/subscribers-lists/"
and when I run this JS in this 2 pages, because 1page code is included in other page:
var baseURL = "http://localhost/gtwhero/public/";
$('#subscribers_list tbody').on( 'click', 'button.details', function () //Handeling Edit Button Click
{
var data = dataTable.row( $(this).parents('tr') ).data();
//alert(data['id']); //id = index of ID sent from server
window.location = window.location.href +'/'+data['id']+'/subscribers';
});
So, it is working for the second URL, but bot working for the first URL.
So, I am getting:
{baseURL} +"users/{user_id}/subscribers-lists/"+{id}+"/subscribers"
for the second URL, but getting error like this:
{baseURL} +"users/{user_id}/subscribers-lists/"+{id}+"/subscribers"+{id}+"/subscribers"
for the first URL.
Is there any solution?
I have done it-
var url = window.location.href;
var userId = (url.match(/\/users\/(\d+)\//) || [])[1];
var subscribers_lists_Id = (url.match(/\/subscribers-lists\/(\d+)\//) || [])[1];

casperjs login form error

I am using this code to login to form. I get error.
var casper = require('casper').create();
var url = "www.example.com";
casper.start(url,function(){
this.echo(this.getTitle());
});
casper.waitForResource(url,function() {
this.fillSelectors("form[method='post']", {
'input[name="userName"]' : 'usr1',
'input[name="password"]': 'pswed1'
}, true);
});
casper.run();
http://prntscr.com/7jkia1
I pretty much copied examples I found on stack but still I get error... what to do to fix this?
It seems that casper is not able to do a selector for form[method='post'] ( using fillSelectors ), its not working for me either. But if you specify any other atribute like name, id, class, enctype, action, etc, it works.
var casper = require('casper').create();
var url = "https://careershub.bbc.co.uk/members/";
casper.start(url,function(){
this.echo(this.getTitle());
});
casper.waitForResource(url,function() {
this.fillSelectors('form#registration-form', {
'input[name="name_first"]' : 'firstname',
'input[name="name_last"]': 'lastname'
}, true);
this.captureSelector('test.png', 'form');
});
casper.run();

How get values variable javascript from razor?

i have soure code :
$("#yes-modal").click(function (e) {
var img = $("#url").val();
window.location = '#Url.Action("DownloadImages", "Hrd", new { id = *value variable img* })';
});
i want get value img, but i have error.
How can do it ? thank you.
Below syntax should work.
window.location = '#Url.Action("DownloadImages", "Hrd", new { id = ' + img + '})';
Let me know if you face any issue.
The razor syntax is a serverside code. It is evaluated while rendering the page from server. But the javascript is evaluated at the client side (browser). So you have to split it like below code.
$("#yes-modal").click(function (e) {
var img = $("#url").val();
var loc = '#Url.Action("DownloadImages", "Hrd")';
var loc += '?id=' + img;
window.location = loc;
});

Categories

Resources