使用Jsoup获取网页指定div内li中所有链接仅得首个,求解决方案
Hey there! Let's sort out your problem and break down how to get all those links properly.
First: Why You're Only Getting the First Link
Looking at your code, the issue is super straightforward—you're using the wrong variable inside your loop!
You declared for (org.jsoup.nodes.Element link : links), but then inside the loop you called links.attr("href") instead of link.attr("href"). The links variable is the entire collection of elements, so calling attr() on it will only return the value from the first element in the set.
Here's your fixed code:
Document document = Jsoup.connect("https://www.ndtv.com/latest?pfrom=home-topnavigation") .userAgent("Mozilla/17.0") .get(); Elements links = document.select("div.nstory_header a"); for (org.jsoup.nodes.Element link : links) { System.out.println("link : " + link.attr("href")); // Use 'link' instead of 'links' here! // System.out.println("text : " + link.text()); // Uncomment this if you want the link text too }
That should now print every link inside those div.nstory_header containers.
How to Get All Links Inside a Specific Div with Jsoup
Getting links from a specific div is all about using precise CSS selectors with Jsoup. Here's a step-by-step breakdown:
Identify your target div: Use its unique identifier (like
id), class name, or other attributes to target it. For example:- If the div has an
id="latest-news", usediv#latest-news - If it has a class
class="article-container", usediv.article-container - You can even chain attributes if needed, like
div[data-section="top-stories"]
- If the div has an
Select all links inside that div: Append
ato your selector to grab every<a>tag within the targeted div. So your selector becomes something likediv#latest-news aordiv.article-container a.Loop through the results: Just like in your fixed code, iterate over the
Elementscollection and uselink.attr("href")to get each individual link.
Example code for a specific div:
// Target div with class "main-content" and get all links inside it Elements specificLinks = document.select("div.main-content a"); for (Element link : specificLinks) { String url = link.attr("href"); // Handle relative URLs if needed (Jsoup can help with this!) // String absoluteUrl = link.absUrl("href"); System.out.println("Link: " + url); }
Pro tip: If the links are relative URLs (like /latest-news instead of https://example.com/latest-news), use link.absUrl("href") to get the full absolute URL automatically.
内容的提问来源于stack exchange,提问作者Ajinkya Phand

