0

jsoupを使用して特定のページからURLを抽出する次のコードがあります。

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * Example program to list links from a URL.
 */
public class ListLinks {
    public static void main(String[] args) throws IOException {

        String url = "http://shopping.yahoo.com";
        print("Fetching %s...", url);

        Document doc = Jsoup.connect(url).get();
        Elements links = doc.getElementsByTag("a");


        print("\nLinks: (%d)", links.size());
        for (Element link : links) {
       print(" * a: <%s>  (%s)", link.absUrl("href") /*link.attr("href")*/, trim(link.text(), 35));     
        }
    }

    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }

    private static String trim(String s, int width) {
        if (s.length() > width)
            return s.substring(0, width-1) + ".";
        else
            return s;
    }
}

私がやろうとしているのは、httpsサイトのみを抽出するクローラーを構築することです。クローラーに最初にシードリンクを指定しhttpsます。次に、すべてのサイトを抽出し、抽出された各リンクを取得して、収集されたURLの特定の数に達するまで同じことを行います。

私の質問:上記のコードは、特定のページのすべてのリンクを抽出できます。のみで始まるリンクを抽出する必要がありますがhttps://、これを実現するには何をする必要がありますか?

4

1 に答える 1

2

のセレクターを使用できますjsoup。彼らはかなり強力です。

doc.select("a[href*=https]");//(This is the one you are looking for)selects if value of href contatins https
doc.select("a[href^=www]");//selects if value of href starts with www
doc.select("a[href$=.com]");//selects if value of href ends with .com.

など..それらを試してみると、正しいものが見つかります。

于 2012-07-05T05:30:24.967 に答える