java中利用URL抓取网页内容

本文介绍了一种使用Java实现的网页内容抓取方法及从抓取到的内容中解析特定信息的技术。通过HttpClient发起请求获取指定URL的网页内容,并利用正则表达式从中提取店铺名称等信息。
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

/**
 * <ul>
 * <li>Function:
 * 		<ul>
 * 		<li>TODO</li>
 * 		</ul>
 * </li>
 * <li>CopyRight
 * </li>
 * <li>author: <a href="http://blog.youkuaiyun.com/wgzhl2008">wgzhl2008</a></li>
 * <li>E-mail: <a href="mailto:wgzhl2008@gmail.com">wgzhl2008@gmail.com</a>
 * <li>Version:1.0</li>
 * <li>Date:2012-3-17 下午01:36:26</li>
 * </ul>
 */
public class FetchShopUtil {
	private static final Logger logger = Logger.getLogger(FetchShopUtil.class);
	/**
	 * @param url
	 * @return
	 * @see 依据网址获取页面内容
	 * @author 	 * @version 1.0
	 * @date 2012-3-17 下午02:04:19
	 */
	public static String fetchHtmlFromWebPage(String url){
		GetMethod getMethod =new GetMethod(url);
		HttpClient client = new HttpClient();
		int status = 0;
		try{
			status = client.executeMethod(getMethod);
			if(status!=HttpStatus.SC_OK){
				//如果不成功,休息3s后再进行一次抓取
				Thread.sleep(1000*3);
				status = client.executeMethod(getMethod);
			}
		}catch (Exception e) {
			getMethod.releaseConnection();
			logger.error("抓取网页内容出错"+e.getMessage(),e);
		}
		String sResponse="";
		if(status==HttpStatus.SC_OK){
			try {
				sResponse=getMethod.getResponseBodyAsString();
			} catch (IOException e) {
				getMethod.releaseConnection();
				logger.error("抓取网页内容出错"+e.getMessage(),e);
			}
		}else{
			logger.info("抓取网页内容失败");
		}
		getMethod.releaseConnection();
		
		return sResponse;
	}
	
	/**
	 * @param html
	 * @return {@link List}
	 * @see 得到店铺名字
	 * @author 
	 * @version 1.0
	 * @date 2012-3-17 下午02:09:01
	 */
	public static List<String> fecthShopName(String html){
		List<String> resultItem = new ArrayList<String>();
		Pattern p1 = Pattern
				.compile("<p(\\s*)class=(\\s*)\"nick\"(\\s*)>(.*?)</p>");
		Matcher m1 = p1.matcher(html);
		String itemContent[] = null;
		while (m1.find()) {
			itemContent = m1.group().split(">");
			for(String s:itemContent){
				int index=s.indexOf("<");
				if(index!=0){
					resultItem.add(s.substring(0,index).trim());
				}
			}
		}
		return resultItem;
	}
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值