[英]CasperJS can't find element using CSS selector or xPath
我正在尝试使用CasperJS在Google搜索上单击“下一步”按钮,但出现以下错误:
CasperError: Cannot dispatch mousedown event on nonexistent selector: #pnnext
该按钮方便#pnnext
有ID #pnnext
标记。 我尝试使用CSS选择器和xPath使用几种不同的方法来执行点击。 它们概述如下:
var casper = require('casper').create({
verbose: true,
logLevel: "debug",
waitTimeout: 20000
});
casper.defaultWaitForTimeout = 20000
var x = require('casper').selectXPath;
var config = {
url: 'https://www.google.co.uk/search?site=&source=hp&q=house&oq=house&gs_l=hp.3..35i39l2j0l2j0i3j0l5.136980.137617.0.137690.7.7.0.0.0.0.106.450.3j2.5.0.starcytweb...0...1.1.62.hp..4.3.302.0.IK858rPmk0I'
};
casper.start(config.url);
/* INSERT CODE HERE */
casper.then(function() {
this.capture('screenshot.png');
console.log('New location is ' + this.getCurrentUrl());
this.page.close();
this.exit();
});
casper.run();
尝试#1
casper.thenClick("#pnnext");
尝试2:
casper.then(function(){
this.evaluate(function() {
document.getElementById('pnnext').click();
});
});
尝试3:
casper.then(function(){
this.evaluate(function() {
document.querySelector('#pnnext').click();
});
});
尝试#4(超时):
casper.waitForSelector("#pnnext", function(){
this.click('#pnnext');
}, function(){ console.log("Time out"); }, 20000);
尝试5:
casper.then(function(){
this.click(x('//*[@id="pnnext"]'));
});
只是附带说明,我也尝试过执行此示例代码无济于事。 难道我做错了什么?
phantomjs -> v1.9.8
casperjs -> v1.1.0-beta3
这是一个Google页面,因此通过PhantomJS在您的桌面浏览器和CasperJS中看起来不会相同。 差异将基于用户代理字符串,视口大小和其他一些指标。
您应该做的一些事情:
casper.capture()
是否包含该元素 casper.getHTML('#nav td:last-child')
1检查应该包含相关元素的子树是否确实包含该元素 这是我看到的标记:
<td style="text-align:left" class="b">
<a style="text-align:left" href="/search?q=house...">
<span style="background-position:-96px 0;width:71px" class="csb"></span>
<span style="display:block;margin-left:53px">Weiter</span>
</a>
</td>
您可以尝试例如基于链接文本的选择器,如下所示:
casper.click(x('//span[text()="Weiter"]/..')); // click the `a` element
1此选择器基于我对google.co.uk的本地化,可能与您的所在地不同。
我使用过这样的解决方案,也许有人会发现它有用:
casper.then(function() {
this.capture('screenshot.png');
console.log('New location is ' + this.getCurrentUrl());
// something like this
this.wait(someNumberInMsecs).then(function() {
this.click("#pnnext");
});
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.