解析一个html网页,读取指定的正文(去新闻广告)

//本例子是以以截取新浪新闻的正文为例子,其他的html类似
@Test
	public boolean getContent(String link) throws Exception {
		// 通过链接得到对应的输入流
		URL url = new URL(link);
		URLConnection urlConnection = url.openConnection();
		InputStream inputStream = urlConnection.getInputStream();

		// 把流存到一个byte[]数组contentByte中
		byte[] contentByte = new byte[1024 * 10];
		byte[] buffer = new byte[1024];
		int i = -1;
		while ((i = inputStream.read(buffer)) != -1) {
			contentByte = byteMerger(contentByte, buffer);
		}

		// 把数组转为字符串,再对字符串进行相应的增删改查.其中把byte[]数组转为String的时候要注意编码,要与link源的编码一致
		String str = new String(contentByte, "gb2312");
		// 下面是对字符串的截取
		int start = str.indexOf("<!-- 正文内容 begin -->");
		int end = str.indexOf("<!-- publish_helper_end -->");
		if (start != -1) {// 如果查找成功,即源文件存在要截取的目标
			// 截取需要的字符串
			String contentStr = str.substring(start, end);

			// 添加必要的html代码,主要转换的格式也要一一对应.添加的html的编码也要一致
			byte[] write1 = "<html xmlns=http://www.w3.org/1999/xhtml><head><meta http-equiv=Content-Type content=\"text/html;charset=GB2312\"><body>"
					.getBytes("GB2312");
			byte[] write = contentStr.getBytes("GB2312");
			byte[] write2 = "</body></html>".getBytes();

			OutputStream outputStream = new FileOutputStream(Environment
					.getExternalStorageDirectory().toString() + "/tmp.html");
			// 用byteMerger方法来连接byte[]数组
			outputStream.write(byteMerger(byteMerger(write1, write), write2));
			outputStream.close();
			return true;
		} else {// 如果失败,就把源文件保存下来.查完出错原因
			FileWriter fw = new FileWriter(Environment
					.getExternalStorageDirectory().toString() + "/aa.txt");
			fw.flush();
			fw.write(str);
			fw.close();
			return false;
		}
	}

	// java 合并两个byte数组
	public static byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
		byte[] byte_3 = new byte[byte_1.length + byte_2.length];
		System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
		System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
		return byte_3;
	}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值