【URL】检索baidu首页将包含超链接的<a ></a> 打印出来

本文介绍了一个简单的Java程序示例,该程序能够抓取并打印出百度首页中的所有超链接。通过使用URL和BufferedReader类,程序能够有效地读取网页内容,并通过字符串操作筛选出超链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值