2012-02-21 54 views

回答

1

假設標籤看起來HTML是這樣的:

<span id="spannyspan" title="the Title of SPAN">The Text</span> 

那麼WebElement將最好走近這樣的:

WebDriver driver = new FirefoxDriver(); 
WebElement theSpan = driver.findElement(By.id("spannyspan")); 
String title = theSpan.getAttribute("title"); 
String label = theSpan.getText(); 
System.out.println(title); // will return "the Title of SPAN" 
System.out.println(label); // will return "The Text" 
// both without apostrophes ofcourse 

如果這沒有幫助,請提供標籤的樣本HTML正嘗試獲取

+0

由於我不知道 - 是最好的如何將非功能性HTML元素的WebElement作爲標籤? – 2012-06-29 08:40:37

+0

如果您需要從跨度獲取文本,那麼是的。想象一下,跨度將保存訂單ID,這可以稍後對數據庫進行驗證... – 2012-06-29 11:35:54

+0

我只是認爲可能有一個類似被動WebElement的東西與減少指令集 – 2012-06-29 11:45:11

-1
Suppose there is a label contain text "hello": 

    <label>hello</label> 

then what you have to do is: 

# first find this element using xpath or css locator and store that into WebElement object: 

    WebElement label = driver.findElement(By.xpath("//label[contains(text(),'hello')]"); 

# After that using getText() method you can get the text of the label element.getText() method return value in string so,store the value in the string variable: 

    String lbltext = label.getText(); 

# After that if you want to print the value then 

    system.out.println("text = "+lbltext); 
+0

請考慮重新格式化您的答案。用這些怪異的粗體文本和未格式化的代碼片段閱讀是非常困難的。請閱讀[我如何寫出一個好答案](https://stackoverflow.com/help/how-to-answer)。 – Clijsters 2017-05-26 09:49:57