【发布时间】:2013-04-13 19:40:33
【问题描述】:
我有一个方法可以接收 URL 并找到该页面上的所有链接。 但是,我担心它是否只获取链接,因为当我检查链接是否正常工作时,有些链接看起来很奇怪。 例如,如果我检查 www.google.com 上的链接,我会得到 6 个断开的链接,它们不返回 http 状态代码,而是说那个断开的链接没有“协议”。 我只是不会想象谷歌会在其主页上有任何损坏的链接。 断开链接之一的示例是:/preferences?hl=en 我在谷歌主页上看不到这个链接的位置。 我很好奇我是否只检查链接,或者我是否有可能提取不应该是链接的代码?
这是检查链接 URL 的方法:
public static List getLinks(String uriStr) {
List result = new ArrayList<String>();
//create a reader on the html content
try{
System.out.println("in the getlinks try");
URL url = new URI(uriStr).toURL();
URLConnection conn = url.openConnection();
Reader rd = new InputStreamReader(conn.getInputStream());
// Parse the HTML
EditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
kit.read(rd, doc, 0);
// Find all the A elements in the HTML document
HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);
while (it.isValid()) {
SimpleAttributeSet s = (SimpleAttributeSet)it.getAttributes();
String link = (String)s.getAttribute(HTML.Attribute.HREF);
if (link != null) {
// Add the link to the result list
System.out.println(link);
//System.out.println("link print finished");
result.add(link);
}
//System.out.println(link);
it.next();
}
}
【问题讨论】: