CasperJS点击谷歌搜索按钮,this.evaluate()javascript

时间:2014-05-03 23:40:57

标签: javascript google-chrome phantomjs casperjs

我现在正在学习Casperjs,我想模仿谷歌搜索(1.填写内容2.点击按钮;不要使用'填写')。 javascript代码在我的Chrome控制台中有效,但在我的CasperJS中无效。任何想法,投诉或与我相同的经历?

等待答案!

var casper = require("casper").create({
    logLevel:"info",
    verbose:true,
});

casper.start("https://www.google.fr/",function(){
    this.evaluate(function(){
        document.getElementById("gbqfq").value="phantomjs";
        document.getElementById("gbqfsa").click();
    });
    //this.fill('form[action="/search"]',{q:'phantomjs'},true);
}).then(function(){
    this.echo(this.getTitle());
});

casper.run();

1 个答案:

答案 0 :(得分:2)

Google根据用户代理字符串的不同构建页面,因此您需要在桌面浏览器中设置一个。

var casper = require("casper").create({
    logLevel:"debug",
    verbose:true,
    pageSettings: {
        userAgent: "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"
    }
});

然后您可以更改该值,但如果您尝试调用click()函数,但没有任何反应,尽管它存在于元素上。

casper.start("https://www.google.fr/").then(function(){
    this.evaluate(function(){
        var qq = document.querySelector("input[name=q]"),
            qb = document.querySelector("button[name=btnK]"),
            iq = document.getElementById("gbqfq"),
            ib = document.getElementById("gbqfba");
        __utils__.echo("Fields: "+JSON.stringify({
            qq: !!qq, // true
            qb: !!qb, // false w/o UA, true w/ UA
            iq: !!iq, // false w/o UA, true w/ UA
            ib: !!ib, // false w/o UA, true w/ UA
        }));
        qq.value="phantomjs";
        //iq.value="phantomjs";
        qb.click(); // nothing happens
        ib.click(); // nothing happens
    });
}).then(function(){
    this.echo(this.getTitle());
    this.capture("result.png");
});

我找不到点击页面上下文按钮的方法。所以这段代码不会产生结果页面。您可以使用fillsendKeys,因为这些会在搜索字段上调用事件处理,自动(即时)执行搜索。您也不需要在true函数中将提交参数设置为fill,因为搜索是即时的。