CasperJS可以't使用CSS选择器或xPath查找元素

CasperJS can't find element using CSS selector or xPath

本文关键字:选择器 xPath 查找 元素 CSS 使用 可以 CasperJS      更新时间:2024-05-15

我正试图使用CasperJS点击谷歌搜索上的"下一步"按钮,但我收到了以下错误:

CasperError: Cannot dispatch mousedown event on nonexistent selector: #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

这是一个谷歌页面,所以它在你的桌面浏览器和通过PhantomJS的CasperJS中看起来不一样。这种差异将基于用户代理字符串、视口大小和其他一些指标。

你应该做的一些事情:

  1. 检查页面是否已实际加载,并且元素是否与casper.capture()一起存在
  2. 检查应该包含有问题元素的子树是否实际包含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");
  });
  ...
});