[英]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.