如何使用XPath表达式在CasperJS中检索元素的属性
How to retrieve attribute of element in CasperJS using an XPath expression
我有一个网页,中间有这个:
<a href="http://foo.com/home.do?SID=3443132">...
我需要使用XPath提取"href"属性。在CasperJS的API中编写了关于此的信息:clientutils.getElementByXPath.
这是我的代码:
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=")]');
});
但它失败了。它返回这个:
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__
试试这个:
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);
});
正如注释中所指出的,您必须在evaluate
回调中使用__utils__
,因为它被注入到页面中。既然你想要href
,你可以使用:
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;
});
});
这可以通过使用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");
});
您还可以使用casper.getElementInfo
来获取元素的完整信息,包括所有属性(但仅包括某些属性)。
相关文章:
- 如何从给定的json中检索元素
- 使用JQuery检索元素数据
- 正在检索元素's的值
- 如何使用XPath表达式在CasperJS中检索元素的属性
- 如何检索元素的 ID 名称
- 从 Django View 以 JSON 形式返回的数据中检索元素
- 从 Backbone.Collection.remove(n) 中检索元素
- 检索元素父索引
- 无法通过jquery检索元素
- 从外部页面检索元素值
- 从外部网页检索元素id
- 通过数组有效地检索元素
- Jquery /如何比较数组,检索元素数量最多的数组
- MVC - Html.操作使用Javascript检索元素,然后将其作为参数传递给Controller,然后返回一个Pa
- 检索元素边距,如果它是's 'auto'
- 从javascript数组中检索元素
- 从Mailchimp存档RSS中检索元素
- 使用jquery从post数据中检索元素
- 如何检索元素'通过其“;值”;
- Node.js-如何在对象/数组中检索元素的值