【问题标题】:How to select the option with specific value or content in the iframe with CasperJS?如何使用 CasperJS 在 iframe 中选择具有特定值或内容的选项?
【发布时间】:2017-03-02 17:26:10
【问题描述】:

我正在使用 CasperJS 进行爬虫,但我首先需要单击某些内容才能完成页面的搜索过程。但我无法通过其值或内容来选择特定选项。

1.单击父框架中的“全部”按钮:

<select name="sort_id" id="sort_id" class="p9"; display: block;" onclick="javascript: window.setTimeout('Hide_Select(&quot;sort_id&quot;,false)',3); showDialog('LIST','SearchList.aspx?ddl_id=sort_id&amp;key=lar~sort_id&amp;EncodingName=',460,360,true);return false;">
        <option value="">All</option>
    </select>

2.跳转到子框架的页面:

<div id="b_div" class="ym-body">
<iframe>
#document
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>
</head>
<body>
  <form method="post" action="SearchList.aspx?ddl_id=sort_id&amp;key=lar%7esort_id&amp;EncodingName=" id="form1">
    <table>
        <tbody>
          <tr>
            <td>
              <select size="2" name="listb_sor" id="listb_sor" onchange="javascript:OptionClick(this,'sort_id');" style="height:300px;width:220px;">
                 <option value="">All</option>
                 <option value="001">OptionA</option>
                 <option value="00001">OptionB</option>

               </select>
               .......
</iframe>

3.我想选择OptionA。如果成功,子框架会自动关闭。但我无法成功选择 OptionA。

目前我的代码是:

casper.then(function(){
    this.click('#sort_id.p9');
    this.page.switchToChildFrame(0);

    this.evaluate(function() {
        var sel = document.querySelectorAll('#listb_sor option');
        sel.val('001').onchange();
    });
});

但是当我被捕获页面时,似乎代码无法成功选择 OptionA。

【问题讨论】:

    标签: javascript jquery iframe casperjs


    【解决方案1】:

    如果 IFrame 有类似的东西,你可以克服 iFrame ID:

    casper.then(function() {
      this.click('#sort_id.p9');
    });
    
    casper.withFrame("IFrameID", function() {
      casper.then(function() {
        this.evaluate(function() {
          var sel = document.querySelectorAll('#listb_sor option');
          sel.val('001').onchange();
        });
      })
      casper.then(function() {
        // do other stuff in the IFrame
      })
    
    });
    
    casper.then(function() {
      // continue outside the IFrame
    });
    

    如果 IFrame 没有 ID,则必须遍历 IFrame 的索引,依赖于页面上的 IFrame:

    ... 
    casper.withFrame(1, function() {
      casper.then(function() {
        this.evaluate(function() {
          var sel = document.querySelectorAll('#listb_sor option');
          sel.val('001').onchange();
        });
      })
      casper.then(function() {
        // do other stuff in the IFrame
      })
    });
    ...
    

    更多信息请看here on the official documentation

    【讨论】:

    • 谢谢!你能告诉我如何获取 iframe 的索引吗?框架没有 ID。
    • 在这种情况下,它是 Page 的第 n 个元素,即 iframe。所以第一个 iframe 是索引 0,第二个索引 1 等等。如果网站上有动态加载的 iframe,则可能会出现问题。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多