casperjs: how do I click a remote div and then update it's class name?

前提是你 提交于 2019-12-12 04:45:45

问题


As a way of learning CasperJS, I am trying to initiate a click event on a div on a remote page, and then change the class name of the div after I have clicked it. The idea is to find the first clickable div, click it, and then mark it as clicked so I can skip over it to other clickable divs. The markup for the div tag on the remote page looks like:

<div class='clickable_div'></div>

I have tried the following casperjs code:

...
casper.then(function() {
    if( this.exists( 'div.clickable_div' ) ) {
        this.evaluate(function() {
            this.click(document.querySelector('div.clickable_div'));
            return document.querySelector('div.clickable_div').setAttribute("className","clicked");
        });
    }
});
...

It doesn't seem to work. First, I don't think I am initiating the mouse click event on the div correctly. What am I missing? Second, when I fetch the updated html, I don't see any changes in the div's class name. Am I going about this step in the wrong way?


回答1:


You're calling this.click within evaluate(), it just can't work as evaluate() executes code within the page DOM context where there's probably no window.click method.

Here's a possibly working script:

var linkSelector = 'div.clickable_div';

casper.then(function() {
    if (!this.exists(linkSelector)) return;
    this.click(linkSelector);
    this.evaluate(function(linkSelector) {
        __utils__.findOne(linkSelector).setAttribute("className", "clicked");
    }, linkSelector);
});

You may want to have better handling of errors and edge cases, but you get the idea.



来源:https://stackoverflow.com/questions/14270861/casperjs-how-do-i-click-a-remote-div-and-then-update-its-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!