2017-03-02 26 views
0

我正在使用CasperJS進行爬網,但我需要先點擊一下才能完成頁面的搜索過程。但我無法通過其值或其內容選擇特定選項。如何使用CasperJS在iframe中選擇特定值或內容的選項?

1.一旦點擊父框架按鈕「全部」:

<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:

<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.與跳轉到子框架頁。如果成功,子框架將自動關閉。但我無法成功選擇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成功地。

回答

0

可以拿到過的IFRAME ID,如果該IFrame得到了這樣的事情:

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的指數,dependend頁面上的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

+0

THX!你能告訴我如何獲得iframe的索引嗎?該框架沒有ID。 – Jeffy

+0

這是頁面的第n個元素,即iframe。所以第一個iframe是索引0,第二個索引1等等。如果在網站上動態加載iframe可能會造成問題。 ;) – dasmelch

相關問題