如何使用Casperjs通过ID提取输入值?[英] How can I extract an input value by id with CasperJS?

问题描述

我有一个问题.我无法从使用JavaScript的ID中提取价值.

我正在打开Goog​​le,搜索一个术语,我想从id的搜索框中获取值.

var casper = require('casper').create({
    verbose: true,
    logLevel: "info"
});
var mouse = require("mouse").create(casper);
var x = require('casper').selectXPath;
var webPage = require('webpage');
var page = webPage.create();
casper.userAgent('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36')
casper.start("http://www.google.com/ncr", function () {
    this.echo(this.getTitle());
}).viewport(1366, 768);

//casper.then(function() {
//this.sendKeys('#gbqfq', 'Duke');
//this.click('#gbqfsa');
//});
casper.waitForSelector(x('//*[@id="gbqfq"]'), function () {
    this.evaluate(function () {
        document.getElementById('gbqfq').value = "samearga";
        this.echo(this.document.getElementById('gbqfq').value);
    });
    console.log("\nEXISTA SELECTORUL!!! -> document.getElementById('gbqfq').value\n");
});

casper.waitForSelector(x('//*[@id="gbqfq"]'), function () {
    this.evaluate(function () {
        document.forms[0].submit();
    });
    console.log("\nSUBMITING!!!\n");
});

casper.wait(4000, function () {
    console.log("\nFAC POZA\n");
    casper.capture('caca.png');
});

casper.run();

推荐答案

有两种可能获得页面上输入值的可能性.

  1. 您可以注册到/a>事件并将其记录在页面上

    // at the beginning of the script
    casper.on("remote.message", function(msg){
        this.echo("remote> " + msg);
    });
    
    // inside of the step
    casper.evaluate(function () {
        document.getElementById('gbqfq').value = "samearga";
        console.log(document.getElementById('gbqfq').value);
    });
    
  2. 或从页面上下文返回字符串

    // inside of the step
    var inputValue = casper.evaluate(function () {
        document.getElementById('gbqfq').value = "samearga";
        return document.getElementById('gbqfq').value;
    });
    casper.echo(inputValue);
    

您必须牢记this的含义.在页面上下文(casper.evaluate的内部)this内部的内部是指window,但window没有echo函数.页面和卡斯珀上下文是彼此不同的(沙盒),您不能仅使用所有变量.更多信息在 docs..

本文地址:https://www.itbaoku.cn/post/1740125.html