Selenium-Java 4.1.4版本获取多文本节点网页元素文本返回空的解决咨询
Hey there, I get exactly what you're dealing with—you can see the "$10.99" on the UI, but your Selenium getText() call is giving you nothing. The root issue here is likely that the text you want is split into separate text nodes inside the <span> element, and Selenium's getText() doesn't always handle this scenario correctly for rendered text.
Let's go through a few reliable solutions to get that "$10.99" string:
1. Use getAttribute("textContent") instead of getText()
The textContent attribute pulls all text from every node inside the target element, including those split text nodes. Then we just clean up any extra whitespace:
WebElement targetSpan = driver.findElement(By.xpath("//div[@class='css-1o5t8tj']//span[1]")); String rawText = targetSpan.getAttribute("textContent"); String formattedText = rawText.trim().replaceAll("\\s+", ""); // Gives you "$10.99"
2. Fetch Text via JavaScriptExecutor
If the first method doesn't work (rare, but possible with some frameworks like Material UI), using JavaScript to directly access the element's content is a foolproof fallback:
WebElement targetSpan = driver.findElement(By.xpath("//div[@class='css-1o5t8tj']//span[1]")); JavascriptExecutor js = (JavascriptExecutor) driver; String rawText = (String) js.executeScript("return arguments[0].textContent;", targetSpan); String formattedText = rawText.trim().replaceAll("\\s+", "");
3. Target the Text Nodes Directly (Advanced)
For super precise control, you can use an XPath query to grab the text nodes inside the span and concatenate them:
JavascriptExecutor js = (JavascriptExecutor) driver; String rawText = (String) js.executeScript( "return document.evaluate('//div[@class=\"css-1o5t8tj\"]//span[1]/text()', document, null, XPathResult.STRING_TYPE, null).stringValue;" ); String formattedText = rawText.trim().replaceAll("\\s+", "");
Why getText() Failed?
Selenium's getText() returns the visible rendered text of an element, but when text is split into multiple standalone text nodes (like your span has separate "$" and "10.99" nodes), sometimes the browser's rendering combines them visually, but getText() doesn't pick up the combined value. textContent, on the other hand, reads all text content directly from the DOM, regardless of how it's split into nodes.
内容的提问来源于stack exchange,提问作者Devleena

