简体   繁体   中英

How to get the first `href` string using jsoup?

My code returns all the links on a webpage, but I would like to get the first link when I google search something for example "android". How do I do that?

  Document doc = Jsoup.connect(sharedURL).get();
                    String title = doc.title();
                    Elements links = doc.select("a[href]");
                    stringBuilder.append(title).append("\n");
                    for (Element link : links) {
                        stringBuilder.append("\n").append(" ").append(link.text()).append(" ").append(link.attr("href")).append("\n");
                    }

Here ids my code

Elements#first and Node#absUrl

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

public class Main {
    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("https://en.wikipedia.org/wiki/Wikipedia").get();
        Elements links = doc.select("a[href]");
        Node node = links.first();
        System.out.println(node.absUrl("href"));
    }
}

Output:

https://en.wikipedia.org/wiki/Wikipedia:Protection_policy#semi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM