2013-04-10 122 views
1

我寫了下面的代碼,運行這段代碼後它返回空的String值。任何人都可以建議我解決這個問題嗎? 這裏我使用了gettext()方法。它不檢索鏈接名稱。爲什麼GetText方法返回空字符串

我的代碼是:

package Practice_pack_1; 

import java.util.List;  

import org.openqa.selenium.By;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.WebElement;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.testng.annotations.AfterTest;  
import org.testng.annotations.BeforeTest;  
import org.testng.annotations.Test; 

public class CheckingUncheckingCheckbox { 
    WebDriver driver; 
    @BeforeTest 
    public void open() 
    { 
    driver=new FirefoxDriver(); 
    driver.navigate().to("http://openwritings.net/sites/default/files/radio_checkbox.html"); 
} 
@AfterTest 
public void teardown() throws InterruptedException 
{ 
    Thread.sleep(3000); 
    driver.quit(); 
} 
@Test 
public void CheckingChkbox() throws InterruptedException{ 
    WebElement parent = driver.findElement(By.xpath(".//*[@id='fruits']")); 
    List<WebElement> children = parent.findElements(By.tagName("input")); 
    int sz= children.size(); 
    System.out.println("Size is: "+sz); 
    for (int i = 0; i <sz; i++) 
    { 
     boolean check= children.get(i).isSelected(); 
     if(check==true) 
     { 
      System.out.println(children.get(i).getText()+ "is selected"); 
     } 
     else 
     { 
      System.out.println(children.get(i).getText()+ "is not selected"); 
     } 
    } 
} 

}

輸出是:

Size is: 3  
is selected  
is not selected 
is selected 
PASSED: CheckingChkbox 

回答

6

關於你的應用程序,你可能需要使用getAttribute("value")而不是getText()作爲getText返回內部文本。

1

如果你去檢查你的頁面HTML沒有內部文本在標籤。所以你不能使用getText()

我假設您正在尋找獲取輸入標籤的價值。如果你檢查你的HTMl,那麼在輸入標籤中有一個值屬性。您可以使用該值讀取, getAttribute("value")

0

嘗試刪除「。」。您的XPath之前,確保你的XPath元素是正確的

試試這個driver.findElement(By.id("fruits")).getText());

0

我改變你編程爲「更好」的一種方式,用java 及其工具的能力。

其實的getText()被用來捕捉文本bewteen標籤等

<input id="input1" value="123"> getText() catches here </input> 

和的getAttribute()捕獲一個指定的屬性的值。

<input id="input1" value=" getAttribute("value") catches here ">123</input> 

這是我的以下版本的代碼。

@Test 
public void CheckingChkbox() throws InterruptedException{ 
    WebElement parent = driver.findElement(By.xpath(".//*[@id='fruits']")); 
    List<WebElement> children = parent.findElements(By.tagName("input")); 
    System.out.println("Size is: "+children.size()); 
    for (WebElement el : children) 
    { 
    if(el.isSelected()) 
    { 
     System.out.println(el.getAttribute("value")+ "is selected"); 
    } 
    else 
    { 
     System.out.println(el.getAttribute("value")+ "is not selected"); 
    } 
    } // end for 
}// end CheckingChkbox() 
相關問題