【问题标题】:Extract https urls using jsoup使用 jsoup 提取 https url
【发布时间】:2012-07-05 04:40:52
【问题描述】:

我有以下代码使用 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:// 开头的链接,我需要做什么才能实现这一点?

【问题讨论】:

  • 有些网站如果来自 HTTP 网站,会自动将用户重定向到 HTTPS 网站,你想要这样的链接吗? (在这种情况下有点困难,因为你必须在这里发起 HTTP 请求)。
  • 谢谢。不,我只是想从互联网上收集 https 网站。

标签: java web-crawler jsoup


【解决方案1】:

您可以使用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.

等等。尝试一下,你会找到正确的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多