[译文]casperjs使用说明-选择器

casperjs的选择器可以在dom下工作,他既支持css也支持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表达式去查找dom元素

如果要查找实例页面里的<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

你也可以选择使用xpath表达式来替代css选择器:

casper.start('http://domain.tld/page.html', function() {

    this.test.assertExists({

        type: 'xpath',

        path: '//*[@class="plop"]'

    }, 'the element exists');

});
为了更容易的去使用和读xpath,selectXPath能给你提供帮助:
var x = require('casper').selectXPath;



casper.start('http://domain.tld/page.html', function() {

    this.test.assertExists(x('//*[@id="plop"]'), 'the element exists');

});

警告:1、当你使用casperjs.fill()去填充fields时,xpath存在使用限制2、PhantomJS只支持css3选择器使用uploadFile method

你可能感兴趣的:(asp)