2016-05-18 23 views
3

我有一堆radio buttons,並希望從標籤中獲取每個人的文本。這是我到目前爲止已經試過:我無法訪問Web元素的文本

IList<IWebElement> radioButtons = wd.FindElements(By.Name("Components[0].Entity.ComponentSubTypeId")); 
foreach (IWebElement i in radioButtons) 
{ 
    Console.WriteLine(i.Text); 
}    

我知道,他們所得到存儲在List,因爲當我刪除.Text從上面,一些OpenQA.Selenium.Firefox.FirefoxWebElement的被寫入到輸出控制檯,用它與位於頁面上的radio buttons的數量完全匹配。

這裏是radio buttons在頁面上的一個的HTML

<li class="optionListItem"> 
    <span class="floatLeftSmallMargin componentTypeOptions"> 
     <input class="required" id="Components_0__Entity_Entity_ComponentTypeId_PublicationGravure" name="Components[0].Entity.ComponentSubTypeId" type="radio" value="-2147380659" /> 
    </span> 
    <span class="optionListItemText componentTypeOptions"> 
         <label for="Components_0__Entity_Entity_ComponentTypeId_PublicationGravure">Publication Gravure</label> 
    <span class="helpButton" data-title="Publication Gravure" data-text="A printing method on a substrate that is subsequently formed into books, magazines, catalogues, brochures, directories, newspaper supplements or other types of printed materials."> 
    </span> 
    </span> 
    <div class="clear"></div> 
</li> 

但同樣,當我追加.Text的索引我在foreach參數,沒有什麼被寫入到輸出控制檯。

回答

3

問題是您的IList<IWebElement> radioButtons不包含標籤。 它只包含沒有任何文字的input。所以當你做.Text你不會看到任何文字。

IList<IWebElement> labels = wd.FindElements(By.CssSelector(".optionListItem .optionListItemText label")); 

現在迭代上labels,並呼籲.Text,你會看到標籤名稱。

+0

這是正確的答案。謝謝LINGS! – kevin

2

爲什麼它返回什麼的原因是因爲單選按鈕確實沒有文字,但你選擇它們,這裏是如何.Text作品的之實踐例如:

<li > 
    <span id="foo">My text</span> 
    <input name="bar" type="radio"/>I'm not part of the radio 
</li> 

現在,讓我們從上面提取文本

//This will return "My text" 
IWebElement spanText= wd.FindElement(By.CssSelector("#foo")).Text 
//This will return empty 
IWebElement spanText= wd.FindElement(By.XpathSelector("//input")).Text 

在你的情況應該是這個樣子

IList<IWebElement> labels = wd.FindElements(By.CssSelector(".optionListItem .optionListItemText label")); 
foreach (IWebElement i in labels) 
{ 
    Console.WriteLine(i.Text); 
} 
+0

也爲此額外信息upvoted這個答案。謝謝拉斐爾! – kevin