2016-09-12 56 views
0

我正在嘗試使用Java自動化Goibibo網站Selenium。點擊標籤中的Sign後,顯示登錄彈出窗口。如何切換到彈出狀態,以便我可以在彈出的Goibibo中輸入詳細信息。我寫了下面的代碼:如何在使用硒的Goibibo網站上登錄

public class Testclass1 { 

    public static void main(String[] args) throws InterruptedException{ 
     System.setProperty("webdriver.chrome.driver", "D://chromedriver_win32//chromedriver.exe"); 
     WebDriver Driver = new ChromeDriver(); 
     Driver.manage().window().maximize();   
     Driver.get("https://www.goibibo.com/"); 
     Thread.sleep(5000); 
    //HANDLE THE POP UP  
      String handle = Driver.getWindowHandle(); 
      System.out.println(handle); 
      // Click on the Button "New Message Window" 
      Driver.findElement(By.linkText("Sign In")).click(); 
      Thread.sleep(3000); 
      // Store and Print the name of all the windows open    
      Set handles = Driver.getWindowHandles(); 
      System.out.println(handles); 
      // Pass a window handle to the other window 
      for (String handle1 : Driver.getWindowHandles()) { 
       System.out.println(handle1); 
       Driver.switchTo().window(handle1); 
       } 
      Thread.sleep(3000); 
      Driver.findElement(By.name("username")).sendKeys("[email protected]"); 
     //WAIT 
    } 
} 

回答

0

開業popup是不是一個新的窗口popup,它只是簡單的HTML登錄彈出現在是iframe可以通過切換簡單地處理,以iframe如下工作代碼: -

import org.openqa.selenium.support.ui.ExpectedConditions; 
import org.openqa.selenium.support.ui.WebDriverWait; 

driver.get("https://www.goibibo.com/"); 
WebDriverWait wait = new WebDriverWait(driver, 10); 

wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Sign In"))).click(); 

//switch to popup iframe to enter login credentials into form 
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("authiframe")); 

//now enter login credentials 
driver.findElement(By.id("id_username")).sendKeys("username"); 
driver.findElement(By.id("id_password")).sendKeys("password"); 

//now click on sign in button 
driver.findElement(By.id("signinBtn")).click(); 

注意: - 爲了更好的方式,您應該使用WebDriverWait明確地等待具有某些ExpectedConditions而不是Thread.sleep()的元素。

+1

謝謝Saurabh。它爲我工作。你可以告訴我你在什麼基礎上輸入「authiframe」,而切換到彈出 –

+0

實際上,這個彈出登錄表單元素存在於iframe中,可以在切換到iframe後找到這就是爲什麼在查找元素之前需要切換iframe。謝謝 –