javascript - 如何: Select Radio Option Button in iFrame Using CasperJS?

标签 javascript iframe radio-button dom-events casperjs

我是 JavaScript 的新手,CasperJS 的新手,等等。但是,我观看了一些 YouTube 视频并使用 CasperJS 完成了一些示例。从这个 Angular 来看,我认为我已经很好地掌握了基础知识,并为我的第一个项目做好了准备,我现在正坚持这个项目。如何单击单选选项按钮?
我不知道这是否是我正在使用的网站所独有的东西,或者是我理解中的一些额外漏洞,但我尝试的任何方法似乎都不起作用。我将不胜感激任何意见;我已经在黑暗中跌跌撞撞很久了……
由于我是新手,我会提供详细信息,以防我做错了什么,或者应该考虑做等。谢谢!
问题
当我打开网站网址时:http://www.ddbst.com/unifacga.html我有四个选择:
enter image description here
所以我右键单击控件并使用 DevTools 获取有关元素的信息:

<input name="selection" value="Upload" id="ID1" type="radio" onclick="this.form.submit()">
<input name="selection" value="MolinspirationJME" id="ID2" type="radio" onclick="this.form.submit()">
<input name="selection" value="Insert" id="ID3" type="radio" onclick="this.form.submit()">
enter code here
<input name="selection" value="DDBSearch" id="ID4" type="radio" checked="checked" onclick="this.form.submit()">
这里我有兴趣 DDB搜索 (选项 4)。我还没有用单选按钮做一个例子,我最初认为我可以做一些像例如value=true,但后来我看到 value 实际上是一个文本字符串,所以我点击按钮查看它的事件状态是什么样的:
<input name="selection" value="DDBSearch" id="ID4" type="radio" checked="checked" onclick="this.form.submit()">
所以我知道我需要以某种方式激活检查的属性,但我无法通过 XPath、ID、名称等来执行此操作。不知道问题出在哪里,我尝试使用网络上的其他示例报告更多错误信息。
Casper 构造函数选项
我将我的 casper 对象设置如下:
var casper = require("casper").create({
    logLevel:"debug",
    verbose:true,               // log messages will be printed out to the console
    pageSettings:{              // the WebPage instance used by Casper will use these settings.
        loadImages: false,      
        loadPlugins: false,
        webSecurityEnabled: false
    },
        onDie: function(){
            console.log("Script complete.");
        },
        // Display message every time any page successfully initializes:
        onPageInitialized: function(){
            console.log("\rPage initialized.\r");
        },
    waitTimeout: 10000,
    stepTimeout: 10000,
        onWaitTimeout: function(){ // invoked when you are waiting for an element to be visible, e.g. after clicking a button, and waitTimeout has been exceeded.
            this.echo("** Wait-TimeOut **");
        },
        onStepTimeout: function(){ // NOT REALLY SURE WHAT THIS IS USED FOR ???
            this.echo("** Step-TimeOut **");
        }
});
试图通过使用代码来捕获额外的错误信息,例如
casper.on('remote.message', log);
casper.on('error', logError);
casper.on('complete.error', logError);
casper.on('page.error', logError);
需要附加功能:
function log(msg){
    console.log("\r");
    console.log('Remote msg>: ', msg);
    console.log("----------------------------------------------------","\r");
}

function logError(msg,traceback){
    console.log("\r");
    console.log(msg);
    console.log(traceback);
    console.log("----------------------------------------------------","\r");
}
不太确定我从哪里得到这个,或者它是如何工作的,但它看起来应该报告额外的错误信息,所以我破产了。
验证页面结构
我在某处读到你应该首先验证页面的结构,所以我基于表单 opeform,其中包含单选选项。在这一点上,我还注意到我真正想要访问的其他输入字段(在选择第 4 选项之后)只是隐藏在页面上——不确定这是否重要?
在我看来,使用表单的隐藏元素会更容易;从而绕过我目前遇到的单选选项问题? (现在只是一个想法在后台燃烧..)
<form name="opeform" method="post" action="http://ddbonline.ddbst.com/OnlinePropertyEstimation/OnlineUNIFACGroupAssignmentSA.exe">
<hr>
<table border="0" style="white-space: nowrap; font-size:10pt;width: 560px; text-align: left;" cellpadding="2" cellspacing="2">
<tbody><tr><td>
<h3>Input Method</h3><input name="selection" value="Upload" id="ID1" type="radio" onclick="this.form.submit()"><b>Upload</b> a Mol- or CTC-file directly from your hard drive<br>
<input name="selection" value="MolinspirationJME" id="ID2" type="radio" onclick="this.form.submit()"><b>Molinspiration JME</b> allows to draw and edit molecules (Java required)<br>
<input name="selection" value="Insert" id="ID3" type="radio" onclick="this.form.submit()"><b>Insert</b> the content of a Molfile in a textfield<br>
<input name="selection" value="DDBSearch" id="ID4" type="radio" onclick="this.form.submit()"><b>DDB Search</b> (retrieves a structure from the chemical structure database ChemDB)</td>
</tr>
</tbody>
</table>
<input type="hidden" id="ID9" name="molstruct" value="">
</form>
所以我使用 CasperJS 断言系统来确保表单在继续之前就位:
var selector = "#unifacga";
casper.then(function(){
    console.log("\r>>> Check if the element exists.");
    console.log(">>> If the element does not exist, the test (i.e. our script) will fail, otherwise it will simply continue.\r");
    this.waitForSelector(selector,
        function pass () {
            this.capture("open.png");
            console.log("\r",">>> Element found");
            console.log("1: ",this.evaluate(function(sel){return !!document.querySelector(sel)},selector));
            console.log("2: ",this.evaluate(function(sel){return document.querySelector(sel).textContent;},selector));
            console.log(">>> Continue.","\r");
        },
        function fail () {
            this.capture("fail.png");
            this.die(">>> Did not load element... something is wrong T_T","\r");
        }
    );
});
到目前为止,一切都是玫瑰和阳光......
尝试 No.1 - XPATH 选择单选选项
我第一次尝试使用 XPath,因为这是很多示例用于单击按钮的内容:
var x = require("casper").selectXPath;
// //*[@id="ID4"] is the XPath statement.
// input type that has the attribute id as radio.
casper.thenClick(x('//*[@id="ID4"]'));
casper.wait(5000).then(function(){
    casper.capture("option_sel4.png");
});
casper.run();
为此我收到如下错误:
enter image description here
它说不存在选择器,但语法看起来是正确的(据我所知),并且 ID 肯定是“ID4”(如上图所示来自 DevTools)。
尝试 No.2 - 按 ID(和名称)选择单选选项
所以我接下来尝试按 ID(和名称)处理对象:
casper.evaluate(function(){
    document.getElementById("ID4").checked=true;
});
casper.run();
现在我得到一个不同的错误:
enter image description here
所以现在我得到一个类型错误。看起来像我使用的 getElementByID 方法可能不会返回对象或其他东西?任何其他变体,例如getElementByName 会导致类似的错误...
尝试 No.3 - Casper.Click
我也试过 CasperJS.click:
casper.then(function() {
  this.click('input[id="ID4"][checked="checked"]');
});
casper.run();
这会导致另一个错误,例如 XPath:
enter image description here
综上所述
我不知道如何解决这个问题。似乎我尝试选择单选选项 4 的所有操作都会导致某种类型的错误;但是,我对 JavaScript 和 CasperJS 的了解还不够,无法解决比我现有的更多问题。到目前为止,我从网上尝试过的其他解决方案对我不起作用。任何帮助将不胜感激。

最佳答案

使用我的功能click2iframe ,不要忘记 --web-security=no选项,例如./casperjs --web-security=no snap.js

function click2iframe(sel_of_the_iframe,sel_in_the_iframe){
var event=document.createEvent('MouseEvents'),element=document.querySelector(sel_of_the_iframe).contentDocument.querySelector(sel_in_the_iframe);event.initMouseEvent('click',1,1,window,1,0,0,0,0,0,0,0,0,0,null); element.dispatchEvent(event);
}
var casper = require('casper').create();
casper.start('http://www.ddbst.com/unifacga.html').wait(5000).then(function(){
this.capture('test0.png');
this.evaluate(function(click2iframe){
click2iframe('iframe[name="ircframe"]','input[id="ID4"]');
},click2iframe);
});
casper.wait(5000).then(function(){this.capture('test.png');}).wait(2000);
casper.run();

奖励示例:click3_iframe功能,如果您需要单击位于第三个 iframe 中的元素:
<iframe id="1"><iframe id="2"><iframe id="3">
<a id="some_id" href="">some text</a>
</iframe></iframe></iframe>

function click3_iframe(sel_of_the_iframe,sel_of_the_iframe2,sel_of_the_iframe3,sel_in_the_iframe){
var event=document.createEvent('MouseEvents'),
element=document.querySelector(sel_of_the_iframe).contentDocument.querySelector(sel_of_the_iframe2).contentDocument.querySelector(sel_of_the_iframe3).contentDocument.querySelector(sel_in_the_iframe);
event.initMouseEvent('click',1,1,window,1,0,0,0,0,0,0,0,0,0,null); element.dispatchEvent(event);
}
click3_iframe("iframe#1","iframe#2","iframe#3","a#some_id");

关于javascript - 如何: Select Radio Option Button in iFrame Using CasperJS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40450775/

相关文章:

javascript - 有什么方法可以使 onClick 全局或 DRY 吗?

javascript - 如何在 wordpress 上移动 iframe?

javascript - 无法使用 jquery 创建新的 iframe

HTML - 对齐单选按钮和文本

html - 带有自定义图像的样式单选按钮

php - 如何使用 PHP 重复单选按钮

javascript - 为什么 typescript 在 useState React 上抛出错误

javascript - 在 div 中嵌入部分元素

javascript - 在 jquery/js 中将元素从数组插入到表中

javascript - JQuery 删除 iframe 中的事件处理程序