[英]Full Link Extraction using java
My goal is to always get the same string (which is the URI in my case) while reading the href property from a link. 我的目标是在从链接读取href属性时始终获取相同的字符串(在我的情况下为URI)。 Example: Suppose think that a html file it have somany links like 例子:假设一个html文件有很多链接,例如
a href="index.html">
but base domain is http://www.domainname.com/index.html a href="index.html">
但基本域是http://www.domainname.com/index.html
a href="../index.html">
but base domain is http://www.domainname.com/dit/index.html a href="../index.html">
但基本域是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? 我如何在Java中做到这一点?
the input is HTML,that is,from a bunch of HTML code it need to extract correct link 输入的是HTML,也就是说,需要从一堆HTML代码中提取正确的链接
You can do this using a fullworthy HTML parser like Jsoup . 您可以使用像Jsoup这样的功能强大的HTML解析器来执行此操作。 There's a Node#absUrl()
which does exactly what you want. 有一个Node#absUrl()
正是您想要的。
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 may have more other (undiscovered) advantages for your purpose as well. 为了您的目的,Jsoup可能还有其他(未发现的)优势。
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"));
}
Use the URL object: 使用URL对象:
URL url = new URL(URL context, String spec) URL url =新URL(URL上下文,字符串规范)
Here's an example: 这是一个例子:
import java.net.*; 导入java.net。*;
public class Test {
public static void main(String[] args) throws Exception {
URL base = new URL("http://www.java.com/dit/index.html");
URL url = new URL(base, "../hello.html");
System.out.println(base);
System.out.println(url);
}
}
It will print: 它将打印:
http://www.java.com/dit/index.html
http://www.java.com/hello.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.