考虑一个 URl www.example.com,它可能有大量链接,有些可能是内部链接,有些可能是外部链接。我想获取所有子链接的列表,甚至不是子子链接,而只是子链接。 E.G 如果有如下四个链接
1)www.example.com/images/main
2)www.example.com/data
3)www.example.com/users
4)www.example.com/admin/data
然后在这四个中只有 2 和 3 是有用的,因为它们是子链接而不是子子链接等等。有没有办法通过 j-soup 实现它。.如果这不能通过j-soup 然后可以向我介绍一些其他的 java API。 另请注意,它应该是最初发送的父 URL 的链接(即 www.example.com)
最佳答案
如果我能理解子链接可以包含一个斜杠,您可以尝试使用此方法来计算斜杠的数量,例如:
List<String> list = new ArrayList<>();
list.add("www.example.com/images/main");
list.add("www.example.com/data");
list.add("www.example.com/users");
list.add("www.example.com/admin/data");
<小时/>
for(String link : list){
if((link.length() - link.replaceAll("[/]", "").length()) == 1){
System.out.println(link);
}
}
link.length()
:统计字符数
link.replaceAll("[/]", "").length()
:计算斜杠的数量
如果差值等于 1,则为正确链接,否则为否。
<小时/>编辑
How will i scan the whole website for sub links?
这个问题的答案是robots.txt文件或Robots exclusion standard ,所以在这里它定义了网站的所有子链接,例如 https://stackoverflow.com/robots.txt ,所以想法是,要阅读此文件,您可以从该网站提取子链接,这里有一段代码可以帮助您:
public static void main(String[] args) throws Exception {
//Your web site
String website = "http://stackoverflow.com";
//We will read the URL https://stackoverflow.com/robots.txt
URL url = new URL(website + "/robots.txt");
//List of your sub-links
List<String> list;
//Read the file with BufferedReader
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
String subLink;
list = new ArrayList<>();
//Loop throw your file
while ((subLink = in.readLine()) != null) {
//Check if the sub-link is match with this regex, if yes then add it to your list
if (subLink.matches("Disallow: \\/\\w+\\/")) {
list.add(website + "/" + subLink.replace("Disallow: /", ""));
}else{
System.out.println("not match");
}
}
}
//Print your result
System.out.println(list);
}
这将向您展示:
[https://stackoverflow.com/posts/, https://stackoverflow.com/posts?, https://stackoverflow.com/search/, https://stackoverflow.com/search?, https://stackoverflow.com/feeds/, https://stackoverflow.com/feeds?, https://stackoverflow.com/unanswered/, https://stackoverflow.com/unanswered?, https://stackoverflow.com/u/, https://stackoverflow.com/messages/, https://stackoverflow.com/ajax/, https://stackoverflow.com/plugins/]
这是一个Demo about the regex that i use .
希望这可以帮助你。
关于java - 使用 jsoup 获取 URL 的子链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43045351/