2016-03-07 44 views
0

我有代碼的工作,但while循環中斷時,它需要20秒,以執行while循環下面。硒webdriver代碼需要時間退出while循環

下面是代碼:

driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS); 
    try { 
     driver.get("website"); 
    } catch (TimeoutException e) { 

     String x = driver.findElement(By.cssSelector("b")).getText(); 



     driver.get("website"); 
     driver.findElement(By.id("479510558845313")).sendKeys(InstagramAievx.spamusernameinput);  driver.findElement(By.id("263795143794707")).sendKeys(InstagramAievx.spamcommentinput); 

     driver.findElement(By.id("u_0_4")).sendKeys(x); 
     driver.findElement(By.id("u_0_5")).click(); 
     while (true){ 
      WebElement button = null; 
      try { 
       button = driver.findElement(By.cssSelector("a[action='cancel']")); 
      } catch (NoSuchElementException ex){ 
       break; 
      } 
      if (button.isDisplayed() == false) { 
       break; 
      } 

      driver.navigate().refresh(); 

      TimeUnit.SECONDS.sleep(5); 
      driver.findElement(By.id("479510558845313")).sendKeys(InstagramAievx.spamusernameinput); 

      driver.findElement(By.id("263795143794707")).sendKeys(InstagramAievx.spamcommentinput); 

      driver.findElement(By.id("u_0_4")).sendKeys(x); 
      driver.findElement(By.id("u_0_5")).click(); 
     } 

     killFirefox(); 
    } 

是什麼導致了這個約20秒延遲的任何想法。

+1

你是如何定義隱式等待的? 'driver.manage()。timeouts()。implicitlyWait()' – Guy

+1

@Guy感謝您的回覆。是的,我發現這是問題所在。這是在30秒,然後我改變了10秒。現在一切都很好。 – AAlzaabi

回答

0

降低隱式等待超時時間不是一個好的解決方案。你的代碼中的問題是你的findElement()等待你設置的任何隱式等待時間,如果元素不在那裏,這是沒用的,所以這也不是一個好的解決方案。

如果您期望某個元素不存在(甚至可能不存在),暫時禁用隱式等待有時是個好主意。

在這種情況下,在while循環甚至開始之前,您已經執行了一些findElement()調用,所以此時不​​再需要隱式等待,因爲您可以確定文檔已被加載。所以你可以在while循環之前將隱含的等待設置爲0秒,然後再回到30秒,並且你沒事。