求助:如何正确将Jsoup的abs:href结果存入数组并遍历
Hey there! Let's fix this issue you're having with storing Jsoup's abs:href values into an array instead of a space-separated string. I've seen this common mistake before, so let's break it down step by step.
abs:href Storage into an Array First, let's pinpoint what's likely going wrong: you're probably concatenating each URL into a single string with spaces instead of adding each one as a separate element to a collection or array. Here's how to fix it properly:
Step 1: Use a Flexible Collection First
Since we don't know how many URLs we'll get upfront, an ArrayList<String> is ideal—it grows dynamically, unlike a fixed-size array.
Step 2: Extract and Store Each abs:href
Loop through your Jsoup-selected elements, grab each abs:href value, and add it directly to the list as a distinct entry.
Step 3: Convert the Collection to a String Array
Once you've collected all URLs, convert the list to a String[] array if you need that specific type for your use case.
Full Code Example
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.List; private static String[] extractLinks(String targetUrl) { List<String> linkList = new ArrayList<>(); try { // Connect to the target URL and parse the document Document doc = Jsoup.connect(targetUrl).get(); // Select all anchor tags that have an href attribute Elements anchorTags = doc.select("a[href]"); for (Element tag : anchorTags) { // Get the absolute URL from the href attribute String absoluteLink = tag.absUrl("href"); // Add each URL to our list as a separate element linkList.add(absoluteLink); } } catch (Exception e) { e.printStackTrace(); } // Convert the list to a String array and return it return linkList.toArray(new String[0]); }
How to Traverse the Resulting Array
Once you have the array, you can loop through it to use each URL individually:
public static void main(String[] args) { String[] websiteAddresses = extractLinks("https://example.com"); // Loop through the array to process each URL for (String address : websiteAddresses) { System.out.println(address); } }
Why Your Original Code Failed
Chances are you had code that looked like this (which creates a space-separated string instead of an array):
// Incorrect approach that builds a single string String linksAsString = ""; for (Element tag : anchorTags) { linksAsString += tag.absUrl("href") + " "; }
This just appends each URL to a single string with spaces, rather than storing each as a separate array element. Using a list first fixes this because every URL gets its own entry in the collection.
内容的提问来源于stack exchange,提问作者Joshua Trimm

