网页抓取 - 无法使用Javascript和WebView单击HTML输入按钮(可能是iframe问题,不确定)

web scraping - Cannot click on HTML input button with Javascript and WebView (Possibly an iframe issue, not sure)

本文关键字:按钮 iframe 不确定 问题 输入 HTML 抓取 单击 WebView Javascript 网页      更新时间:2023-09-26

我正在开发一个iOS应用程序,该应用程序使用注入的javascript在Web视图中执行一些操作。我正在尝试按下路由器网络界面上的提交按钮(所以我不能给你一个网址)。我在网上尝试了许多其他建议的解决方案,但没有任何效果。我必须做的一件事是单击类型=SUBMIT的输入按钮,无论出于何种原因,它都没有响应。我尝试使用 .click() 以及调用 onClick 事件处理程序,但没有任何效果。任何帮助,不胜感激。HTML 代码如下:

<div class="fix_button">
  <table width="100%" border="0" cellpadding="0" cellspacing="2">
    <tbody>
      <tr>
        <td nowrap="" colspan="2" align="center">
          <input class="cancel_bt" type="RESET" name="Cancel" value="Cancel" onclick="doCancel();" languagecode="51">
          &nbsp;
          <input class="apply_bt" type="SUBMIT" name="Apply" value="Apply" onclick="return checkData();" languagecode="50">
        </td>
      </tr>
    </tbody>
  </table>
</div>

输入按钮是带有class="apply_bt"的按钮。此div 位于一个 iframe 中,并提交此帧内另一个 iframe 中的数据。结构是这样的:

<iframe>
    // Contains the Apply Button
    <div class="fix_button"></div>
    // Contains the iframe where the info to be submitted is
    <div id="main" class="main_top_button">
        // Contains data to be submitted
        <iframe src="WLG_2g_wireless2.htm&amp;todo=wifi_primary_init" id="2g_setting" name="wl2gsetting" onload="SetCwinHeight(this.id)" marginheight="0" marginwidth="0" scrolling="no" width="100%" frameborder="0" height="288px">
        </iframe>
    </div>
</iframe>

这是我用来单击按钮的代码:

// Gets the outer iframe
iframe1 = document.getElementById("formframe");
// Gets the html within the iframe
var innerDoc=iframe1.contentDocument || iframe1.contentWindow.document;
// Gets iframe within the iframe
innerframe = innerDoc.getElementById("2g_setting");
// Gets the html within the inner iframe
var innerDoc2=innerframe.contentDocument || innerframe.contentWindow.document;
// I Enter some data in the inner iframe (not shown), this portion 
// of the code works perfectly. I can see fields being entered and 
// buttons being clicked.
// Then I click the apply button...
innerDoc.getElementsByName("Apply")[0].click()
// And nothing happens

我能够获取元素并从应用按钮读取数据,例如其文本,但我无法在按钮上执行 .click() 操作。另外,我没有收到任何错误。我不知道为什么它不起作用。请帮忙!

click 方法仅对<a>标签可靠。您应该改为触发合成事件。这也将保证调用任何事件处理程序,无论它们是设置为 html 属性、element.onclick、addEventListener 还是您可能正在使用的任何库。

请参阅如何触发 JavaScript 事件点击

使用上述问题中的代码,执行以下操作。

var button = innerDoc.getElementsByName("Apply")[0] ;
fireEvent(button, 'click')

问题是脚本在另一个 iFrame 中,因此如果您不在 iFrame 内,它将无法抓取它。因此,onclick 事件将失败。必须先从内部 Iframe 获取函数,才能从外部 iFrame 运行它们。