要掃描網頁上的鏈接,您可以使用JSoup庫。如前面的回答表明可以用來
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
class read_data {
public static void main(String[] args) {
try {
Document doc = Jsoup.connect("**your_url**").get();
Elements links = doc.select("a");
List<String> list = new ArrayList<>();
for (Element link : links) {
list.add(link.attr("abs:href"));
}
} catch (IOException ex) {
}
}
}
列表。
閱讀網站上所有鏈接的代碼如下所示。我已使用http://stackoverflow.com/
進行說明。我建議你先瀏覽公司的terms of use,然後再揪出網站。
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class readAllLinks {
public static Set<String> uniqueURL = new HashSet<String>();
public static String my_site;
public static void main(String[] args) {
readAllLinks obj = new readAllLinks();
my_site = "stackoverflow.com";
obj.get_links("http://stackoverflow.com/");
}
private void get_links(String url) {
try {
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a");
links.stream().map((link) -> link.attr("abs:href")).forEachOrdered((this_url) -> {
boolean add = uniqueURL.add(this_url);
if (add && this_url.contains(my_site)) {
System.out.println(this_url);
get_links(this_url);
}
});
} catch (IOException ex) {
}
}
}
您將獲得uniqueURL
字段中所有鏈接的列表。
但是,我將如何掃描整個網站的子鏈接 –
你的實現將工作後,我會得到網站上的所有內部鏈接 –
檢查我的編輯@javafan的想法是閱讀** robots.txt **它包含網站的所有信息,所以你可以從那裏提取子鏈接 –