You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jsoup获取网页指定div内li中所有链接仅得首个,求解决方案

Hey there! Let's sort out your problem and break down how to get all those links properly.

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.

Getting links from a specific div is all about using precise CSS selectors with Jsoup. Here's a step-by-step breakdown:

  1. 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", use div#latest-news
    • If it has a class class="article-container", use div.article-container
    • You can even chain attributes if needed, like div[data-section="top-stories"]
  2. Select all links inside that div: Append a to your selector to grab every <a> tag within the targeted div. So your selector becomes something like div#latest-news a or div.article-container a.

  3. Loop through the results: Just like in your fixed code, iterate over the Elements collection and use link.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:16:13