我有以下代码,使用 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
站点,然后获取每个提取的链接并对它们执行相同的操作,直到达到一定数量的收集网址。
我的问题:上面的代码可以提取给定页面中的所有链接。我需要提取仅以 https://
开头的链接,我需要做什么才能实现此目的?
最佳答案
您可以使用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.
等等……尝试一下,你就会找到正确的。
关于java - 使用 jsoup 提取 https url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11337931/