5
我有一种方法可以接收URL并找到该页面上的所有链接。 但是我担心它是否仅仅考虑链接,因为当我检查链接是否正常工作时,一些链接看起来很奇怪。 例如,如果我检查www.google.com上的链接,我会得到6个断开的链接,它们不会返回http状态码,而是表示没有该协议链接。 我只是不会想象谷歌会在其主页上有任何断开的链接。 其中一个中断链接的示例是:/ preferences?hl = en 我看不到此链接位于Google主页上。 我很好奇,如果我检查链接或是否有可能我提取不应该是链接的代码?我是否只使用此Java代码检查URL的链接?
下面是检查链接的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();
}
}
谢谢,我知道你的意思,我只是不知道如何编码它。如果(链接!= uriStr + href)将链接添加到链接的前面。像那样的东西? – user1835504 2013-04-20 15:33:56
对不起,只是刚学习java。 – user1835504 2013-04-20 15:35:17
我会这样做:'if(!“http”.regionMatches(true,0,link,0,4)){link = uriStr + link; }'。这样,您就不必担心区分大小写的链接或小于4个字符的hrefs。不必感到难过。很高兴帮助:) – 2013-04-20 15:36:04