【问题标题】:CasperJS can't find element using CSS selector or xPathCasperJS 无法使用 CSS 选择器或 xPath 找到元素
【发布时间】:2015-04-28 04:26:20
【问题描述】:

我正在尝试使用 CasperJS 在 Google 搜索中单击“下一步”按钮,但出现以下错误:

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

顺便说一句,我也尝试过执行此sample code 无济于事。我做错了吗?


phantomjs -> v1.9.8

casperjs -> v1.1.0-beta3

【问题讨论】:

    标签: javascript xpath css-selectors casperjs


    【解决方案1】:

    这是一个 Google 页面,因此它在您的桌面浏览器和通过 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 的本地化,对你来说可能不一样。

    【讨论】:

      【解决方案2】:

      我用过这样的解决方案,也许有人会觉得它有用:

      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");
        });
      
        ...
      });
      

      【讨论】:

        猜你喜欢
        • 2016-03-24
        • 2020-03-05
        • 1970-01-01
        • 2012-09-03
        • 1970-01-01
        • 1970-01-01
        • 2021-11-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多