问题
id = casper.evaluate(function() {
return Array.prototype.map.call(document.querySelectorAll("image"),
function(e) {return e.getElementById();});});
this.echo(id);
回答1:
--Update--
If you want get elements containing a specific class
just use a helper function to scrape the elements you are looking for.
Example:
var casper = require('casper').create();
var ids = [];
function getIdsByClassValue() {
// use your selector here eg. '.image'.
var elems = document.querySelectorAll('input[type="submit"]');
return Array.prototype.map.call(elems, function (e) {
// change to the attribute you are looking for.
return e.getAttribute('value')
});
}
casper.start('https://www.google.com/');
casper.then(function () {
ids = this.evaluate(getIdsByClassValue);
});
casper.run(function() {
this.echo('\n - ' + ids.join('\n - ')).exit();
});
You can use getElementsAttribute
to do that.
.getElementsAttribute
Signature: getElementsAttribute(String selector, String attribute)
Retrieves the values of an attribute on each element matching the provided selector:
Here is an example.
var ids = [];
var casper = require('casper').create();
casper.start('https://google.com/', function() {
this.wait(1000, function() {
ids = this.getElementsAttribute('*', 'id')
.filter(function(id) {
return id.length > 0;
})
});
});
casper.then( function() {
this.echo('\n - ' + ids.join('\n - ')).exit();
})
casper.run();
回答2:
return e.getElementById();
does obviously not make any sense, because getElementById is a function that expect one argument and is only available on the document
.
It seems you want to return the id property:
var ids = casper.evaluate(function() {
return Array.prototype.map.call(document.querySelectorAll("image"), function(e) {
return e.id;
});
});
this.echo(ids);
来源:https://stackoverflow.com/questions/43932139/i-need-to-extract-all-id-values-with-casperjs