1.检索baidu首页将包含超链接的<a ></a> 打印出来
(如<a href="http://news.baidu.com">新 闻</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">新 闻</a>
<a href="http://tieba.baidu.com">贴 吧</a>
<a href="http://zhidao.baidu.com">知 道</a>
<a href="http://mp3.baidu.com">MP3</a>
<a href="http://image.baidu.com">图 片</a>
<a href="http://video.baidu.com">视 频</a>
<a href="http://map.baidu.com">地 图</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/">更多>></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>