`

遍历网站的所有Url

    博客分类:
  • HTML
阅读更多

网站的url分为很多种类:<a href="" />; <form action="" method="Get"/>;<link href=""/>;<img src=""/>;<script src=""/> ;<frame src=""/> 等等

难点:
递归遍历
获得页面每个url
同时请求(每种类型的请求方式都不同)
有些链接是重复的,需要去重

使用 Htmlparse 工具 下载htmlparser.jar
遍历 + 通过htmlparser 解析页面元素
Java代码 复制代码
  1. public class Urll {   
  2.   
  3.     // 定义的全局变量   
  4.     public static Vector<String> svecOutUrl = new Vector<String>();   
  5.     public static Vector<String> svecBadUrl = new Vector<String>();   
  6.     public static Vector<String> svecAUrl = new Vector<String>();   
  7.     public static final int DEEP=3//遍历的深度   
  8.     public static boolean bl; //判断标志   
  9.     private static String loc;   
  10.     private static Parser parser; //对超文本进行分析   
  11.        
  12.   
  13.     private static String hostName = "sina.com";   
  14.        
  15.        
  16.        
  17.        
  18.        
  19.     // 由于网站中URL之间的连接构成了图,所以对图的遍历这里采用深度优先的方法。   
  20.     public static void extractLinks(String loc) throws Exception {   
  21.   
  22.         String str1;   
  23.         URL wwwurl;   
  24.         boolean byes;   
  25.            
  26.         Vector<String> vecUrl=new Vector<String>();   
  27.            
  28.         // 解析 <a>   
  29.         try {   
  30.             parser = new Parser(loc); //原理见HTMLParser   
  31.             bl=true;   
  32.         }   
  33.         catch (Exception e) {   
  34.             bl=false;   
  35.             e.printStackTrace();   
  36.         }   
  37.            
  38.         filterStr = "a";   
  39.         filter = new TagNameFilter(filterStr);   
  40.         links = parser.extractAllNodesThatMatch(filter);    
  41.         for (int i = 0;i < links.size();i++) {   
  42.             if(bl)   
  43.             {   
  44.                 byes=true;   
  45.                 LinkTag LinkTag = (LinkTag)links.elementAt(i);   
  46.                 str1= LinkTag.getLink();   
  47.                 System.out.println(""+i);   
  48.                                 str1 = Patter (str1)   
  49.                 if(str1.equals("")) continue;   
  50.                 if(!svecAUrl.contains(str1))   
  51.                 {   
  52.                     try  
  53.                     {   
  54.                         // 判断是否可连接   
  55.                         wwwurl=new URL(str1);   
  56.                         URLConnection con = wwwurl.openConnection();   
  57.                         con.setConnectTimeout(1000);   
  58.                         con.getInputStream();   
  59.                     }   
  60.                     catch(SocketTimeoutException e)   
  61.                     {   
  62.                         byes=false;   
  63.                         svecBadUrl.add(str1);   
  64.                         continue;   
  65.                     }   
  66.                     catch(Exception e)   
  67.                     {   
  68.                         byes=false;   
  69.                         continue;   
  70.                     }   
  71.                     if(GetHostName(str1).equals(hostName))   
  72.                     {   
  73.                         svecAUrl.add(str1);   
  74.                         vecUrl.add(str1);   
  75.                     }   
  76.                     else  
  77.                     {   
  78.                         svecOutUrl.add(str1);   
  79.                     }   
  80.                 }   
  81.             }   
  82.         }   
  83.        
  84.            
  85.            
  86.         //  递归调用   
  87.         String strNew;   
  88.         int b = 1;   
  89.         if(b<=DEEP)   
  90.         {   
  91.   
  92.             for(int i=0;i<vecUrl.size();i++)   
  93.             {   
  94.                 strNew=(String)vecUrl.get(i);   
  95.                 extractLinks(strNew);    
  96.             }   
  97.         }   
  98.   
  99.     }   
  100.            
  101.        
  102.     // 通过该函数来判断所得URL是否是本网站的URL   
  103.     public static String GetHostName(String host)   
  104.     {   
  105.         URL aurl;   
  106.         String ss=" ";   
  107.         try  
  108.         {   
  109.             aurl=new URL(host);   
  110.             ss=aurl.getHost();   
  111.             ss = ss.substring(ss.length()-10, ss.length());   
  112.         }   
  113.         catch(Exception e)   
  114.         {   
  115.             e.printStackTrace();   
  116.         }   
  117.         return ss;   
  118.     }   
  119.        
  120. }     
public class Urll {

	// 定义的全局变量
	public static Vector<String> svecOutUrl = new Vector<String>();
	public static Vector<String> svecBadUrl = new Vector<String>();
	public static Vector<String> svecAUrl = new Vector<String>();
	public static final int DEEP=3; //遍历的深度
	public static boolean bl; //判断标志
	private static String loc;
	private static Parser parser; //对超文本进行分析
	

	private static String hostName = "sina.com";
	
	
	
	
	
	// 由于网站中URL之间的连接构成了图,所以对图的遍历这里采用深度优先的方法。
	public static void extractLinks(String loc) throws Exception {

		String str1;
		URL wwwurl;
		boolean byes;
		
		Vector<String> vecUrl=new Vector<String>();
		
		// 解析 <a>
		try {
			parser = new Parser(loc); //原理见HTMLParser
			bl=true;
		}
		catch (Exception e) {
			bl=false;
			e.printStackTrace();
		}
		
		filterStr = "a";
        filter = new TagNameFilter(filterStr);
        links = parser.extractAllNodesThatMatch(filter); 
		for (int i = 0;i < links.size();i++) {
			if(bl)
			{
				byes=true;
				LinkTag LinkTag = (LinkTag)links.elementAt(i);
				str1= LinkTag.getLink();
				System.out.println(""+i);
                                str1 = Patter (str1)
				if(str1.equals("")) continue;
				if(!svecAUrl.contains(str1))
				{
					try
					{
						// 判断是否可连接
						wwwurl=new URL(str1);
						URLConnection con = wwwurl.openConnection();
						con.setConnectTimeout(1000);
						con.getInputStream();
					}
					catch(SocketTimeoutException e)
					{
						byes=false;
						svecBadUrl.add(str1);
						continue;
					}
					catch(Exception e)
					{
						byes=false;
						continue;
					}
					if(GetHostName(str1).equals(hostName))
					{
						svecAUrl.add(str1);
						vecUrl.add(str1);
					}
					else
					{
						svecOutUrl.add(str1);
					}
				}
			}
		}
	
		
		
		//	递归调用
		String strNew;
		int b = 1;
		if(b<=DEEP)
		{

			for(int i=0;i<vecUrl.size();i++)
			{
				strNew=(String)vecUrl.get(i);
				extractLinks(strNew); 
			}
		}

	}
		
	
	// 通过该函数来判断所得URL是否是本网站的URL
	public static String GetHostName(String host)
	{
		URL aurl;
		String ss=" ";
		try
		{
			aurl=new URL(host);
			ss=aurl.getHost();
			ss = ss.substring(ss.length()-10, ss.length());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return ss;
	}
	
}	


去重需要使用正则表达式
Java代码 复制代码
  1. private String Patter (String str) {   
  2.        
  3.     if (str.indexOf("http:") == -1) {   
  4.         return str = "";   
  5.     }   
  6.   
  7.     Pattern p = Pattern.compile("http://www.sina.com/\\d+/v/\\d+.html");   
  8.     Matcher  m = p.matcher(str);   
  9.     boolean  b = m.matches();   
  10.     if (b) {   
  11.         str = "http://www.sina.com/0/v/0.html";   
  12.         return str;   
  13.     }   
	private String Patter (String str) {
		
		if (str.indexOf("http:") == -1) {
			return str = "";
		}

		Pattern	p = Pattern.compile("http://www.sina.com/\\d+/v/\\d+.html");
		Matcher  m = p.matcher(str);
		boolean  b = m.matches();
		if (b) {
			str = "http://www.sina.com/0/v/0.html";
			return str;
		}
}


二、用htmlparse 可以对 a ,link,script,img 元素获取,但无法解决对form的递归提交,因为form提交方式分为get,post两种,对post方式参数列表无法获取,无法动态设置post提交方式。
使用HttpUnit测试工具很好强大的模拟浏览器,可以任意提交,页面元素也可以获得。
下载引入 httpunit.rar
Java代码 复制代码
  1.        
  2.     private static WebConversation wc = new WebConversation();     
  3.     private static WebForm w;   
  4.   
  5. // 由于网站中URL之间的连接构成了图,所以对图的遍历这里采用深度优先的方法。   
  6.     public static void extractLinks(WebRequestSource webT,String method,boolean start) throws Exception {   
  7.   
  8.         Vector<WebForm> vecForm=new Vector<WebForm>();   
  9.         Vector<WebLink> vecLink=new Vector<WebLink>();   
  10.         WebResponse resp = null;   
  11.         WebForm[] webForm = new WebForm[0];   
  12.         WebLink[] webLink = new WebLink[0];   
  13.         try {   
  14.             HttpUnitOptions.setExceptionsThrownOnScriptError(false);   
  15.             // 按照 Get Post link 类型打开web   
  16.   
  17.             if (start) {   
  18.                 // 首页   
  19.                 WebRequest req = new PostMethodWebRequest("http://www.sina.com/");   
  20.                 resp = wc.getResponse(req);   
  21.             } else if ("post".equals(method) || "get".equals(method)) {   
  22.                                //获得form 并提交   
  23.                 WebForm w = (WebForm) webT;   
  24.                 [color=red]resp = w.submit();[/color]   
  25.             } else {   
  26.                 WebLink l = (WebLink) webT;   
  27.                 [color=red]resp = l.click();[/color]   
  28.             }   
  29.             webForm = resp.getForms();   
  30.             webLink = resp.getLinks();   
  31.   
  32.             bl=true;   
  33.         } catch (Exception e) {   
  34.             bl=false;   
  35.             e.printStackTrace();   
  36.         }   
  37.   
  38.         String ss,str1;   
  39.         URL wwwurl;   
  40.         boolean byes;   
  41.         StringBuffer strUrl;   
  42.         int a=0,b=0,tID=0;   
  43.         b++;   
  44.            
  45.            
  46.            
  47.            
  48.         // 获取一个页面中所有的FORM中URL   
  49.         for (int i = 0;i < webForm.length;i++) {   
  50.             if(bl) {   
  51.                 byes=true;   
  52.                 // 按照 Get Post 类型    
  53.                 strUrl = new StringBuffer(resp.getURL().toString());   
  54.                    
  55.                 if (!"./".equals(webForm[i].getAction()) && "post".equals(webForm[i].getMethod())) {   
  56.                     strUrl.append(webForm[i].getAction().substring(1, webForm[i].getAction().length()));   
  57.                     strUrl.append("?");   
  58.                     String[] para = webForm[i].getParameterNames();   
  59.                     for (int p = 0;p< para.length;p++) {   
  60.                         strUrl.append(para[p]);   
  61.                         strUrl.append("=&");   
  62.                     }   
  63.                 } else if (!"./".equals(webForm[i].getAction())) {   
  64.                     strUrl.append(webForm[i].getAction().substring(1, webForm[i].getAction().length()));   
  65.                 }   
  66.                    
  67.                 if(strUrl.equals("")) continue;   
  68.   
  69.                 if(!svecLink.contains(strUrl.toString())) {   
  70.                     try {   
  71.                         // 按照 Get Post 类型    
  72.                         if (!"./".equals(webForm[i].getAction())) {   
  73.                             webForm[i].submit();   
  74.                         }   
  75.                     } catch(Exception e) {   
  76.                         byes=false;   
  77.                     }   
  78.                     if(GetHostName(strUrl.toString()).equals(hostName) && byes){   
  79.                         a++;   
  80.                         tID++;   
  81.                         svecLink.add(strUrl.toString());   
  82.                         // 按照 Get Post 类型    
  83.                         vecForm.add(webForm[i]);   
  84.                     } else {   
  85.                         svecOutlink.add(strUrl.toString());   
  86.                     }   
  87.                        
  88.                     if (svecLink.size() >= 1000) {   
  89.                         svecLink.clear();   
  90.                     }   
  91.                 }   
  92.             }   
  93.         }   
  94.            
  95.         // 获取一个页面中所有的LINK中URL   
  96.         for (int i = 0;i < webLink.length;i++) {   
  97.             if(bl) {   
  98.                 byes=true;   
  99.                 // 按照 Link 类型    
  100.                 strUrl = new StringBuffer(webLink[i].getURLString());   
  101.                    
  102.                 if (strUrl.indexOf("http") == -1) {   
  103.                     strUrl = new StringBuffer();   
  104.                 }   
  105.                 if(strUrl == null || "".equals(strUrl.toString())) continue;   
  106.   
  107.                 if(!svecLink.contains(strUrl.toString())) {   
  108.                     try {   
  109.                             webLink[i].newScriptable();   
  110.                             HttpUnitOptions.clearScriptErrorMessages();   
  111.                             HttpUnitOptions.setExceptionsThrownOnScriptError(false);   
  112.                             HttpUnitOptions.setScriptingEnabled(false);   
  113.                             HttpUnitOptions.setJavaScriptOptimizationLevel(0);   
  114.                             WebRequest re = webLink[i].getRequest();   
  115.                             URL u = re.getURL();   
  116.                             u.getContent();   
  117.                             // 按照 Link 类型    
  118.                     } catch(Exception e) {   
  119.                         byes=false;   
  120.                         System.out.print(e.getMessage());   
  121.                     }   
  122.                     if(GetHostName(strUrl.toString()).equals(hostName) && byes){   
  123.                         a++;   
  124.                         tID++;   
  125.                         svecLink.add(strUrl.toString());   
  126.                         // 按照 Link 类型    
  127.                         vecLink.add(webLink[i]);   
  128.                     } else {   
  129.                         svecOutlink.add(strUrl.toString());   
  130.                     }   
  131.                        
  132.                     if (svecLink.size() >= 1000) {   
  133.                         svecLink.clear();   
  134.                     }   
  135.                 }   
  136.             }   
  137.         }   
  138.   
  139.            
  140.         WebForm webFNew;   
  141.         WebLink webLNew;   
  142.         if(a>0&&b<=DEEP) {   
  143.   
  144.             //  递归调用   
  145.             for(int i=0,j=0;i<vecForm.size()||j<vecLink.size();i++,j++) {   
  146.                 webFNew = (WebForm)vecForm.get(i);   
  147.                 extractLinks(webFNew,webFNew.getMethod().toString(),false);    
  148.                    
  149.                 webLNew = (WebLink)vecLink.get(j);   
  150.                 extractLinks(webLNew,"link".toString(),false);    
  151.                    
  152.             }   
  153.         }   
  154.   
  155.     }   
  156.        
  157.        
  158.        
  159.        
  160.        
  161.     // 通过该函数来判断所得URL是否是本网站的URL,如果不是就不需要添加svecLink中如果是并且以前没有提取过就添加到svecLink中。   
  162.     public static String GetHostName(String host) {   
  163.         URL aurl;   
  164.         String ss=" ";   
  165.         try {   
  166.             aurl=new URL(host);   
  167.             ss=aurl.getHost();   
  168.             ss = ss.substring(ss.length()-10, ss.length());   
  169.         } catch(Exception e) {   
  170.             e.printStackTrace();   
  171.         }   
  172.         return ss;   
  173.     }   
  174.        
  175. }  
	
	private static WebConversation wc = new WebConversation();	
	private static WebForm w;

// 由于网站中URL之间的连接构成了图,所以对图的遍历这里采用深度优先的方法。
	public static void extractLinks(WebRequestSource webT,String method,boolean start) throws Exception {

		Vector<WebForm> vecForm=new Vector<WebForm>();
		Vector<WebLink> vecLink=new Vector<WebLink>();
		WebResponse resp = null;
		WebForm[] webForm = new WebForm[0];
		WebLink[] webLink = new WebLink[0];
		try {
			HttpUnitOptions.setExceptionsThrownOnScriptError(false);
			// 按照 Get Post link 类型打开web

			if (start) {
				// 首页
				WebRequest req = new PostMethodWebRequest("http://www.sina.com/");
				resp = wc.getResponse(req);
			} else if ("post".equals(method) || "get".equals(method)) {
                               //获得form 并提交
				WebForm w = (WebForm) webT;
				[color=red]resp = w.submit();[/color]
			} else {
				WebLink l = (WebLink) webT;
				[color=red]resp = l.click();[/color]
			}
			webForm = resp.getForms();
			webLink = resp.getLinks();

			bl=true;
		} catch (Exception e) {
			bl=false;
			e.printStackTrace();
		}

		String ss,str1;
		URL wwwurl;
		boolean byes;
		StringBuffer strUrl;
		int a=0,b=0,tID=0;
		b++;
		
		
		
		
		// 获取一个页面中所有的FORM中URL
		for (int i = 0;i < webForm.length;i++) {
			if(bl) {
				byes=true;
				// 按照 Get Post 类型 
				strUrl = new StringBuffer(resp.getURL().toString());
				
				if (!"./".equals(webForm[i].getAction()) && "post".equals(webForm[i].getMethod())) {
					strUrl.append(webForm[i].getAction().substring(1, webForm[i].getAction().length()));
					strUrl.append("?");
					String[] para = webForm[i].getParameterNames();
					for (int p = 0;p< para.length;p++) {
						strUrl.append(para[p]);
						strUrl.append("=&");
					}
				} else if (!"./".equals(webForm[i].getAction())) {
					strUrl.append(webForm[i].getAction().substring(1, webForm[i].getAction().length()));
				}
				
				if(strUrl.equals("")) continue;

				if(!svecLink.contains(strUrl.toString())) {
					try {
						// 按照 Get Post 类型 
						if (!"./".equals(webForm[i].getAction())) {
							webForm[i].submit();
						}
					} catch(Exception e) {
						byes=false;
					}
					if(GetHostName(strUrl.toString()).equals(hostName) && byes){
						a++;
						tID++;
						svecLink.add(strUrl.toString());
						// 按照 Get Post 类型 
						vecForm.add(webForm[i]);
					} else {
						svecOutlink.add(strUrl.toString());
					}
					
					if (svecLink.size() >= 1000) {
						svecLink.clear();
					}
				}
			}
		}
		
		// 获取一个页面中所有的LINK中URL
		for (int i = 0;i < webLink.length;i++) {
			if(bl) {
				byes=true;
				// 按照 Link 类型 
				strUrl = new StringBuffer(webLink[i].getURLString());
				
				if (strUrl.indexOf("http") == -1) {
					strUrl = new StringBuffer();
				}
				if(strUrl == null || "".equals(strUrl.toString())) continue;

				if(!svecLink.contains(strUrl.toString())) {
					try {
							webLink[i].newScriptable();
							HttpUnitOptions.clearScriptErrorMessages();
							HttpUnitOptions.setExceptionsThrownOnScriptError(false);
							HttpUnitOptions.setScriptingEnabled(false);
							HttpUnitOptions.setJavaScriptOptimizationLevel(0);
							WebRequest re = webLink[i].getRequest();
							URL u = re.getURL();
							u.getContent();
							// 按照 Link 类型 
					} catch(Exception e) {
						byes=false;
						System.out.print(e.getMessage());
					}
					if(GetHostName(strUrl.toString()).equals(hostName) && byes){
						a++;
						tID++;
						svecLink.add(strUrl.toString());
						// 按照 Link 类型 
						vecLink.add(webLink[i]);
					} else {
						svecOutlink.add(strUrl.toString());
					}
					
					if (svecLink.size() >= 1000) {
						svecLink.clear();
					}
				}
			}
		}

		
		WebForm webFNew;
		WebLink webLNew;
		if(a>0&&b<=DEEP) {

			//	递归调用
			for(int i=0,j=0;i<vecForm.size()||j<vecLink.size();i++,j++) {
				webFNew = (WebForm)vecForm.get(i);
				extractLinks(webFNew,webFNew.getMethod().toString(),false); 
				
				webLNew = (WebLink)vecLink.get(j);
				extractLinks(webLNew,"link".toString(),false); 
				
			}
		}

	}
	
	
	
	
	
	// 通过该函数来判断所得URL是否是本网站的URL,如果不是就不需要添加svecLink中如果是并且以前没有提取过就添加到svecLink中。
	public static String GetHostName(String host) {
		URL aurl;
		String ss=" ";
		try {
			aurl=new URL(host);
			ss=aurl.getHost();
			ss = ss.substring(ss.length()-10, ss.length());
		} catch(Exception e) {
			e.printStackTrace();
		}
		return ss;
	}
	
}


对于不符合链接格式的都会无法请求 也就是坏链接。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics