我是 Jsoup 的新手,我想进行屏幕抓取以获取链接层次结构。我能够从第一页获取链接,但我需要知道如何更深入并获取每个链接的链接。这就是我到目前为止所拥有的。它打印出所有 URL,但我想更深入地打印每个 URL,或者如果它太多,至少我想选择一个 URL 示例“* a: http://www.w3schools.com/html/ default.asp (Learn HTML)" 它是从输出和打印它的所有子 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://www.w3schools.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;
}
}
输出:
Fetching http://www.w3schools.com/...
Links: (127)
* a: <> ()
* a: <http://www.w3schools.com/html/default.asp> (Learn HTML)
* a: <http://www.w3schools.com/html/html5_intro.asp> (Learn HTML5)
* a: <http://www.w3schools.com/css/default.asp> (Learn CSS)
* a: <http://www.w3schools.com/css3/default.asp> (Learn CSS3)
...
...
还有更多网址,但我不想全部显示