使用Java的完整链接提取 [英] Full Link Extraction using java

查看:69
本文介绍了使用Java的完整链接提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在从链接读取href属性时始终获取相同的字符串(在我的情况下为URI).例子:假设认为一个html文件具有许多链接,例如
a href ="index.html"> ,但基本域为 http://www.domainname.com/index.html
a href ="../index.html"> ,但基本域为 http://www.domainname.com/dit/index.html
我如何正确获取所有链接意味着包括域名在内的完整链接?
我该如何在Java中做到这一点?
输入的是HTML,也就是说,需要从一堆HTML代码中提取正确的链接

My goal is to always get the same string (which is the URI in my case) while reading the href property from a link. Example: Suppose think that a html file it have somany links like
a href="index.html"> but base domain is http://www.domainname.com/index.html
a href="../index.html"> but base domain is http://www.domainname.com/dit/index.html
how can i get all the link correctly means the full link including domain name?
how can i do that in java?
the input is HTML,that is,from a bunch of HTML code it need to extract correct link

推荐答案

您可以使用诸如 Jsoup .有一个 Node#absUrl() 正是您想要的.

You can do this using a fullworthy HTML parser like Jsoup. There's a Node#absUrl() which does exactly what you want.

package com.stackoverflow.q3394298;

import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class Test {
    
    public static void main(String... args) throws Exception {
        URL url = new URL("https://stackoverflow.com/questions/3394298/");
        Document document = Jsoup.connect(url).get();
        Element link = document.select("a.question-hyperlink").first();
        System.out.println(link.attr("href"));
        System.out.println(link.absUrl("href"));
    }
    
}

为当前问题的标题链接打印(正确)以下内容:

which prints (correctly) the following for the title link of your current question:


/questions/3394298/full-link-extraction-using-java
https://stackoverflow.com/questions/3394298/full-link-extraction-using-java

出于您的目的,Jsoup可能还有其他(未发现的)优势.

Jsoup may have more other (undiscovered) advantages for your purpose as well.

更新:如果要在文档中选择所有链接,请执行以下操作:

Update: if you want to select all links in the document, then do as follows:

        Elements links = document.select("a");
        for (Element link : links) {
            System.out.println(link.attr("href"));
            System.out.println(link.absUrl("href"));
        }

这篇关于使用Java的完整链接提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆