WebDriver(Java)获取label标签文本值失败问题排查
Hey there! Let's break down what's going on here. First off, your XPath isn't the problem — if it were, your code would throw a NoSuchElementException instead of just returning an empty string. The issue lies in how you're trying to retrieve the text from the label element.
Why your current code fails
The <label> tag's content ("Results found: 2") is part of the element's text node, not stored in a value attribute. When you call getAttribute("value"), you're asking for a property that doesn't exist on this label element, which is why you get an empty result.
The fix
To get the text content of the label, use one of these methods instead:
Use
getText()(most reliable for visible text):
This is the standard way to retrieve visible text from an element in WebDriver.WebElement tf = driver.findElement(By.xpath("//label[@id='busquedaSimpleForm:j_idt36']")); String fdl = tf.getText(); System.out.println(fdl);Fallback options (for edge cases):
IfgetText()doesn't work (e.g., the text is hidden or rendered in a way WebDriver doesn't recognize), you can use these attribute-based approaches to access the raw text content:// Get raw text content including hidden text String fdl = tf.getAttribute("textContent"); // Or get text as it appears visually (similar to getText()) String fdl = tf.getAttribute("innerText");
Quick note
Remember: The value attribute is typically used for form elements like <input> or <select>, not for container elements like <label> that hold text directly.
内容的提问来源于stack exchange,提问作者Prabu

