当前位置: 首页 > 文档资料 > CasperJS 中文文档 >

选择器

优质
小牛编辑
137浏览
2023-12-01

选择器

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>

CSS3

在默认情况下,CasperJS接受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();

如果你使用的是测试框架,你应该这样写:

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();
    });
});

其他方便的测试方法都依赖于选择器:

casper.test.begin('Page content tests', 3, function suite(test) {
    casper.start('http://domain.tld/page.html', function() {
        test.assertExists('h1.page-title');
        test.assertSelectorHasText('h1.page-title', 'Hello');
        test.assertVisible('footer');
    }).run(function() {
        test.done();
    });
});

XPath

版本0.6.8新增 同样的,你可以使用XPath表达式作为选择器。

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

为了简化XPath表达式的阅读,CasperJS提供了一个selectXPath助手模块来帮助你:

var x = require('casper').selectXPath;

casper.start('http://domain.tld/page.html', function() {
    this.test.assertExists(x('//*[@id="plop"]'), 'the element exists');
});
警告

CasperJS中唯一对XPath的限制是当你想在casper.fill()方法中填写文件字段时;PhantomJS本身只允许在其uploadFile方法中使用CSS3选择器,这加强了这个限制。