2017-04-02 5 views
0

を抽出しようとしているときに、私はすべてのネストされたのiframeのSRC属性を取得しようとしていますが、私は古い参照exception.Hereを取得しています古い要素参照の例外を取得すると、コードは、ネストされたのiframeのsrc属性

public class findAllSources { 

    ArrayList<String> sources = new ArrayList<String>(); 

    @Test 
    public void iframeTest() { 
     System.setProperty("webdriver.chrome.driver", "path to chrome driver"); 
     ChromeDriver driver = new ChromeDriver(); 
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
     driver.get("https://www.engadget.com/"); 
     List<WebElement> allFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]")); 
     for (WebElement frame : allFrames) { 
      if(frame.isDisplayed()){ 
        System.out.println("We clicked frame "+frame); 
        System.out.println(" with a source "+frame.getAttribute("src")); 
        sources.add(frame.getAttribute("src")); 
        driver.switchTo().frame(frame); 
        findDeeperFrames(driver); 
        driver.switchTo().defaultContent(); 
      } 
     } 
    } 

    public void findDeeperFrames(ChromeDriver driver){ 

     List<WebElement> deeperFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]")); 
     for (WebElement nframe: deeperFrames) { 
      if (nframe.isDisplayed()){ 

       if (!nframe.getAttribute("src").isEmpty()){ 
       sources.add(nframe.getAttribute("src")); 
       System.out.println("Nested source "+ nframe.getAttribute("src"));} 

       driver.switchTo().frame(nframe); 
       findDeeperFrames(driver); 
       //getting out of the frame 
       driver.switchTo().defaultContent(); 
      } 
     } 
    } 
} 

は、いずれかがあるのさ私の目標を達成するための他のアプローチですか?

答えて

0

更新日:driver.switchTo().defaultContent();を使用した後、あなたのコードはまだ新しいフレームおよびそれらの要素に切り替える前に、最初に保存したallFrames webElementリストを使用しているfor LOOPの次の繰り返しになるので

あなたのコードは、StaleExcceptionErrorを返しますもはやDOMには付けられません。ですから、以下に示すように、再びそのフレームのリストを識別しなければならないことを避けるために:

List<WebElement> deeperFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]")); 


for (int j=1; j<=deeperFrames.size(); j++) { 


      List<WebElement> myFrames = driver.findElements(By.xpath("//iframe")); 

      WebElement nframe = myFrames.get(j-1); 


      if (nframe.isDisplayed()) 
      { 
       if (!nframe.getAttribute("src").isEmpty()){ 
      sources.add(nframe.getAttribute("src")); 
      System.out.println("Nested source "+ nframe.getAttribute("src"));} 

      driver.switchTo().frame(nframe); 
      findDeeperFrames(driver); 
      //getting out of the frame 
      driver.switchTo().defaultContent(); 

      } 
} 
+0

私はあなたが別のフレームorwindowにスイッチを試してみて、その後、後にするとき、あまりにも –

+0

古い例外があり、このコードで同じエラーが出ます元のウィンドウに戻ります。切り替え前に以前に保存されていたWeb要素を使用しようとすると、その行がそのエラーをスローします。 – kushal

+0

if(nframe.isDisplayed()){} –

関連する問題