我正在尝试获取网站中的链接,并将它们放在列表
上,但在没有根站点的情况下,我经常获得不完整的链接。例如,我得到类似 /thing.html/
而不是 http://website.com/thing.html/
它是一个搜索引擎,所以我也需要解析网站的链接,并且我需要完整的链接才能做到这一点。
我也不允许使用任何第三方库,例如 JSoup,这就是为什么我使用 javax.swing.text.html
来做到这一点。
我认为你可以使用 Jsoup 做类似 anchor.attr("abs:href")
的事情,这与我在这里需要的东西是一样的。
这是我到目前为止的代码:
import java.util.List;
import java.util.ArrayList;
import java.net.*;
import java.io.*;
import javax.swing.text.html.parser.ParserDelegator;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.MutableAttributeSet;
public class PARSER {
public static List<String> getLinks(BufferedReader BuffRead) throws IOException {
final ArrayList<String> list = new ArrayList();
ParserDelegator parserDelegator = new ParserDelegator();
ParserCallback parserCallback = new ParserCallback() {
public void handleText(final char[] data, final int pos) { }
public void handleStartTag(Tag tag, MutableAttributeSet attribute, int pos) {
if (tag == Tag.A) {
String address = (String) attribute.getAttribute(Attribute.HREF);
//This is where I get the HREF "links"
list.add(address);
}
}
public void handleEndTag(Tag t, final int pos) { }
public void handleSimpleTag(Tag t, MutableAttributeSet a, final int pos) { }
public void handleComment(final char[] data, final int pos) { }
public void handleError(final java.lang.String errMsg, final int pos) { }
};
parserDelegator.parse(BuffRead, parserCallback, false);
return list;
}
最佳答案
首先:考虑不要以大写字母 Parser
或 MyParser
的方式编写类名,起始大写就足够了;)
如果您只抓取一个网站,则可能有很多相关链接可供查找。在内部使用它们是很常见的,对于相对链接,您得到的结果是正确的。您知道您正在解析的网站上有外部链接吗?
我不知道你在什么环境下调用你的解析器,但如果你只是调用 Parser.getLinks(someBuffer)
而不知道你正在解析的网站,你只会留下你想要的链接寻找。如果您正在解析在线网站,只需添加基本网址即可。由于您知道您现在所在的网站,因此您可以传递 url 并将其添加到您的相对链接中:
方法接口(interface)看起来像这样
public static List<String> getLinks(BufferedReader BuffRead, String baseUrl) throws IOException
你会检查类似的相对链接(这很简单)
if (tag == Tag.A) {
String address = (String) attribute.getAttribute(Attribute.HREF);
//if(!address.startsWith("http")) should work too as a primitive absolute link
//often starts with "http" as protocol
if(address.startsWith("/")||address.startsWith("..")){
address = baseUrl + address;
}
list.add(address);
}
问候
关于java - 如何使用 javax.swing.text.html 从 HREF 标记获取完整/绝对链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29273682/