2012-07-05 66 views
0

我有以下代码使用jsoup从给定网页提取网址。使用jsoup提取https网址

import org.jsoup.Jsoup; 
import org.jsoup.helper.Validate; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Element; 
import org.jsoup.select.Elements; 

import java.io.IOException; 

/** 
* Example program to list links from a URL. 
*/ 
public class ListLinks { 
    public static void main(String[] args) throws IOException { 

     String url = "http://shopping.yahoo.com"; 
     print("Fetching %s...", url); 

     Document doc = Jsoup.connect(url).get(); 
     Elements links = doc.getElementsByTag("a"); 


     print("\nLinks: (%d)", links.size()); 
     for (Element link : links) { 
     print(" * a: <%s> (%s)", link.absUrl("href") /*link.attr("href")*/, trim(link.text(), 35));  
     } 
    } 

    private static void print(String msg, Object... args) { 
     System.out.println(String.format(msg, args)); 
    } 

    private static String trim(String s, int width) { 
     if (s.length() > width) 
      return s.substring(0, width-1) + "."; 
     else 
      return s; 
    } 
} 

我想要做的,是建立一个只提取https网站履带。我给爬虫一个种子链接开始,然后它应该提取所有https网站,然后采取每个提取的链接,并对他们做同样的事情,直到达到一定数量的收集的网址。

我的问题:上面的代码可以提取给定页面中的所有链接。我需要提取仅以https://开头的链接,为了实现此目的,我需要做些什么?

+0

有些网站会自动将用户重定向到HTTPS站点,如果他们来自HTTP站点,您是否需要这样的链接? (在这种情况下,这比较困难,因为您必须在此启动HTTP请求)。 – nhahtdh

+0

谢谢。不,我只想从互联网上收集https网站。 –

回答

2

您可以使用jsoup的选择器。他们非常强大。

doc.select("a[href*=https]");//(This is the one you are looking for)selects if value of href contatins https 
doc.select("a[href^=www]");//selects if value of href starts with www 
doc.select("a[href$=.com]");//selects if value of href ends with .com. 

等等。用它们进行实验,你会发现正确的。