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