java - 使用 jsoup 提取 https url

标签 java web-crawler jsoup

我有以下代码,使用 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/

相关文章:

java - Android - 使用游标适配器在 ListView 中格式化时间戳

java - 如何知道java进程等待了多少时间

python - 如何制作可以下载带有各自URL的图像的图像爬虫

javascript - 爬虫可以完全用javascript写吗?

java - 如何使用selenium优化java中的向下滚动代码

Java : How to parse date format to show specific output format?

java - 在Java集合框架中如何确保循环链表的所有对象至少被遍历一次而不重复?

r - 有没有办法在原始数据中添加文本(链接)?

java - 如何迭代一组链接并提取 href 并将它们存储在新的集合中?

java - System.out.print 删除 Matcher 类异常