2014-07-13 47 views
1

假設我想模擬一個場景,其中用戶想要一個接一個地看到所有可摺疊內容,如一個等待,兩次點擊之間(在大約2-3秒)使用Selenium Webdriver顯示手風琴中的所有可摺疊內容

用戶單擊第1部分,然後等待2秒鐘,然後單擊第2部分,依此類推。

我想用這種方式

package com.rahul.misc; 
import java.util.List; 
import java.util.concurrent.TimeUnit; 

import org.openqa.selenium.By; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.interactions.Actions; 

public class accordion { 
public WebDriver driver; 
private String baseUrl; 

public static void main(String[] args) { 
accordion acc=new accordion(); 
acc.checkFirefox(); 
    // TODO Auto-generated method stub 

} 
public void checkFirefox(){ 
driver=new FirefoxDriver(); 
driver.manage().window().maximize(); 
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 

baseUrl="http://jqueryui.com/accordion/"; 
driver.get(baseUrl); 


List<WebElement> allinks= driver.findElements(By.cssSelector(".ui-accordion-header")); 
for(WebElement w:allinks){ 
    new Actions(driver).click().build().perform(); 
    try { 
     Thread.sleep(3000); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

}}

此代碼編譯正確實施,但它什麼都不做。我對我把所有元素放在列表中的部分持懷疑態度。這是捕獲小部件的所有Web元素的正確方法。如果沒有,我該怎麼做。

也是行爲執行正確嗎?因爲在這種情況下,用戶不會這樣做,他只需點擊可摺疊標題即可。

回答

3

您的代碼沒有做任何事情的原因是因爲元素包含在iframe中。如果沒有找到元素,findElements()不會引發異常,因此您的代碼將完成運行。

您可以修復的部分,像這樣:

baseUrl="http://jqueryui.com/accordion/"; 
driver.get(baseUrl); 
driver.switchTo().frame(driver.findElement(By.cssSelector(".demo-frame"))); 

一旦你在iframe做,你就需要切換回來了,像這樣:

driver.switchTo().defaultContent(); 

我相信你」會遇到這條線上的另一個問題:

new Actions(driver).click().build().perform(); 

click() in a Actions上下文點擊鼠標當前位置。由於你沒有告訴鼠標指向哪裏,它是點擊某處,而不是你想要的元素。你可以通過幾種不同的方法解決這個問題。

我會推薦這:

w.click(); 

如果你想留在Actions鏈,就可以解決這個問題是這樣的:

new Actions(driver).click(w).build().perform(); 
+0

非常感謝你。它完美。忘記了iframe的事情。 – demouser123