【URL】檢索baidu首頁將包含超鏈接的 打印出來

1.檢索baidu首頁將包含超鏈接的<a ></a> 打印出來
(如<a href="
http://news.baidu.com">新&nbsp;聞</a>  這種形式打印)

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author $KangMiao$
 * 檢索百度首頁將包含超鏈接的行打印出來
 * 就是把包含"<a"的行打印出來
 */

public class PrintURLInfo01 {
	private String path;

	public PrintURLInfo01(String path) {
		super();
		this.path = path;
	}
	
	//打印有超鏈接的url方法
	public void printUrl() {
		try {
			URL url = new URL(path);
			BufferedReader br = new BufferedReader(new InputStreamReader(url
					.openStream()));
			String temp = "",str = "";
			int a = 0,b = 0;
			while ((temp = br.readLine()) != null) {
		//indexOf("",int)帶兩個參數的,後面參數是指從哪個索引處開始查;這裏用while是因爲讀取的一行中可能包含多個超鏈接
			   while(temp.indexOf("<a href=",b)!=-1){
				 a = temp.indexOf("<a href=",b+1);
				 b = temp.indexOf("a>",a);
				 str = temp.substring(a, b+2);
				 System.out.println(str);
				}
			 //還原0,表示重新從0索引處開始查找
			   a = 0;  
			   b = 0;
			}
			br.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		PrintURLInfo01 print = new PrintURLInfo01("http://www.baidu.com");
		print.printUrl();

	}
}

 打印結果如下:

 

<a href="/gaoji/preferences.html">設置</a>
<a href="http://passport.baidu.com/?login&tpl=mn">登錄</a>
<a href="http://news.baidu.com">新&nbsp;聞</a>
<a href="http://tieba.baidu.com">貼&nbsp;吧</a>
<a href="http://zhidao.baidu.com">知&nbsp;道</a>
<a href="http://mp3.baidu.com">MP3</a>
<a href="http://image.baidu.com">圖&nbsp;片</a>
<a href="http://video.baidu.com">視&nbsp;頻</a>
<a href="http://map.baidu.com">地&nbsp;圖</a>
<a href="#" name="ime_hw">手寫</a>
<a href="#" name="ime_py">拼音</a>
<a href="#" name="ime_cl">關閉</a>
<a href="http://hi.baidu.com">空間</a>
<a href="http://baike.baidu.com">百科</a>
<a href="http://www.hao123.com">hao123</a>
<a href="/more/">更多&gt;&gt;</a>
<a href="http://e.baidu.com/?refer=888">加入百度推廣</a>
<a href="http://top.baidu.com">搜索風雲榜</a>
<a href="http://home.baidu.com">關於百度</a>
<a href="http://ir.baidu.com">About Baidu</a>
<a href="/duty/">使用百度前必讀</a>
<a href="http://www.miibeian.gov.cn" target="_blank">京ICP證030173號</a>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章