如何使用CasperJS通过id提取输入值

如何使用CasperJS通过id提取输入值

本文介绍了如何使用CasperJS通过id提取输入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个casperjs问题.我无法使用javascript从ID中提取值.

I have a casperjs problem. I can't extract value from an id with javascript.

我正在打开google,搜索一个词,并且我想通过id从搜索框中获取值.

I am opening google, searching a term, and i want to get the value from the searchbox by 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();

推荐答案

有两种方法可以获取页面上输入的值.

There are two possibilities to get the value of an input on the page.

  1. 您可以注册到 remote.message 事件并将其记录在页面上

  1. You can either register to remote.message event and log it on the page

// 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);
});

  • 或从页面上下文返回字符串

  • or return the string from the page context

    // 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函数. Page和Casper上下文是彼此不同的(沙盒),您不能只使用所有变量. 文档中的更多内容.

    You have to keep in mind what this means. Inside of the page context (inside of casper.evaluate) this refers to window, but window doesn't have an echo function. Page and casper contexts are distinct from one another (sandboxed) and you can't just use all variables. More in the docs.

    这篇关于如何使用CasperJS通过id提取输入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-05 09:18