使用JSoup查找HTML中div标签内的Span标签内容
Hey there! Great job getting started with Jsoup—you're already pulling content from divs, so grabbing that span text is just a small tweak. Let's break it down.
Your Target HTML Structure
$35 raised
The Solution
You have two simple ways to target that span:
1. Directly Select the Span via Its Parent Div
You can chain the selectors to target the span inside the _6wab div directly. Use the .text() method instead of .html() here—this pulls just the text content of the element, not the surrounding tags.
Document doc = Jsoup.connect("https://" + line).userAgent("Mozilla/17.0").get(); // Grab the span text directly String raisedAmount = doc.select("div._6wab span").text(); // If you want to ensure you only get the first matching span (in case there are multiple) String raisedAmount = doc.select("div._6wab span").first().text();
2. First Select the Div, Then Its Child Span
If you prefer to break it into steps (maybe for readability or if you need the div for other things), you can first select the parent div, then grab its child span:
Document doc = Jsoup.connect("https://" + line).userAgent("Mozilla/17.0").get(); // Get the parent div element Element targetDiv = doc.selectFirst("div._6wab"); // Now get the span text from the div String raisedAmount = targetDiv.select("span").text();
Quick Note on .html() vs .text()
In your original code, you used .html() to get the text from <div class="_6wae">Time</div>—that works because the div has no child elements, so .html() returns the same as .text(). But when dealing with nested elements like your span inside a div, .text() is the right choice to skip the <span> tags and get just the content you want.
内容的提问来源于stack exchange,提问作者user12075259

