您的位置:首页 > 编程语言 > ASP

casperjs中Selectors使用总结

2015-10-16 21:43 501 查看
整理一下最近学习的casperjs的Selectors部分内容。

CasperJS makes a heavy use of selectors in order to work with the DOM, and can transparently use either CSS3 or

XPath expressions.

就是说casperjs处理DOM文档的搜索器主要是CSS3或者XPath表达式。

举例说明一下两者的使用:

我们首先列举html标签

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My page</title>
</head>
<body>
<h1 class="page-title">Hello</h1>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<footer><p>©2012 myself</p></footer>
</body>
</html>

1 CSS3
casperjs允许使用CSS3搜索字符串对DOM文档进行查找相应的元素。

举例说明一下使用CSS3去查找<h1 class="page-title">标签:

var casper = require('casper').create();
casper.start('http://domain.tld/page.html', function() {
if (this.exists('h1.page-title')) {
this.echo('the heading exists');
}
});
casper.run();

或者也可以使用test测试框架:
casper.test.begin('The heading exists', 1, function suite(test) {
casper.start('http://domain.tld/page.html', function() {
test.assertExists('h1.page-title');
}).run(function() {
test.done();
});
});

2 XPath

为了实现搜索DOM文档标签我们也可以使用XPath

casper.start('http://domain.tld/page.html', function() {
this.test.assertExists({
type: 'xpath',
path: '//*[@class="plop"]'
}, 'the element exists');
});

以上XPath的使用方式较为繁琐,在casper模块中的selectXPath中的helper可以
var x = require('casper').selectXPath;
casper.start('http://domain.tld/page.html', function() {
this.test.assertExists(x('//*[@id="plop"]'), 'the element exists');
});

值得注意的一点是:XPath唯一一个使用限制就是casper.fill()方法中仅可以使用CSS3,XPath不可用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: