java网络爬虫,使用apache httpClient

                 

                 我是从官网下载的最新版本,windows操作系统选zip版本就行了。

                 在网上搜的一些资料,感觉提供的类有点旧了。新下载的包没有相关类,用法也不对。对了,我下载的版本是4.3.6。


                 所以只能自己搜索资料摸索,在下载的包中有相应的guide指导,还有一些现成的例子。


                我自己写了一个简单的例子:

        1.doGet方法用于获取不需要登录的网站数据,完全没有问题

        2.doPost只对特定的网站有用,比如用户名,密码不加密明文传输的。它的升级版可以参照牛人的博客,针对新浪微博模拟登陆,爬取数据。    


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 最简单的HTTP客户端,用来演示通过GET,post方式访问某个页面
 * 
 * @author napoleonjk
 */
public class SimpleClient {

	public static void main(String[] args) {

		SimpleClient client = new SimpleClient();
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 简易get
		String uri = "http://www.baidu.com";
		client.doGet(uri, httpclient);
		System.out.println("----------------------------");
		// 模拟登录post访问
		uri = "https://xxxxxxx/account/login";
		client.doPost(uri, "xxxxx", "xxxxx", httpclient);
	}

	// get方式
	public void doGet(String uri, CloseableHttpClient httpclient) {
		// 创建HttpGet,将要请求的URL通过构造方法传入HttpGet对象。
		HttpGet httpget = new HttpGet(uri);
		try {
			CloseableHttpResponse response = httpclient.execute(httpget);
			formatHtml(response);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// post方式
	public void doPost(String uri, String username, String password,
			CloseableHttpClient httpclient) {
		try {
			// 创建HttpPost,将要请求的URL通过构造方法传入HttpPost对象
			HttpPost post = new HttpPost(uri);
			post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) "
					+ "AppleWebKit/535.11 (KHTML, like Gecko) "
					+ "Chrome/17.0.963.83 " + "Safari/535.11");
			String login_type = "username";// 也可能是别的校验方式,例如HTTP Basic
											// Authentication,处理就不同了
			String cookietime = "0";
			String btn_submit = "%E7%99%BB%E5%BD%95";
			// 登录表单的信息
			List<NameValuePair> qparams = new ArrayList<NameValuePair>();
			qparams.add(new BasicNameValuePair("login_type", login_type));
			qparams.add(new BasicNameValuePair("stu_no", username));
			qparams.add(new BasicNameValuePair("password", password));
			qparams.add(new BasicNameValuePair("cookietime", cookietime));
			qparams.add(new BasicNameValuePair("btn_submit", btn_submit));

			UrlEncodedFormEntity params = new UrlEncodedFormEntity(qparams,
					"UTF-8");
			post.setEntity(params);
			CloseableHttpResponse response = httpclient.execute(post);
			Document doc = formatHtml(response);
			// ----------------------------再次访问页面中其他超链接
			Elements aTags = doc.getElementsByTag("a");//获取页面中的超链接
			if (aTags.size()>0) {
				Element aElement = aTags.get(0);//取数组中的第一个超链接
				Attributes attributes = aElement.attributes();
				String newUri = attributes.get("href");
				doGet(newUri, httpclient);//get方式爬取新页面
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
     //使用Jsoup格式化爬取的网页内容
	private Document formatHtml(CloseableHttpResponse response)
			throws ParseException, IOException {
		// 相当于按了下确定登录的按钮,也就是浏览器调转了
		HttpEntity httpEntity = response.getEntity();
		String entityMsg = EntityUtils.toString(httpEntity);
		Document doc = Jsoup.parse(entityMsg);
		String msg = doc.html();// 获取原生页
		System.out.println(msg);
		return doc;
	}

}

相关类库:

Apache HttpClient  :http://hc.apache.org/downloads.cgi

Jsoup                      :http://jsoup.org/download

注意点:1.代理问题

              一开始,想爬取百度的首页,老是报告以下错误,后来发现是因为公司使用的代理,需要进行代理设置。

             java.net.UnknownHostException: www.baidu.com

             我嫌麻烦,索性访问本地正在做的项目的地址,结果成功获取页面内容。

             2.多线程并发访问,设置访问间隔,模拟登陆,登录校验类型,增加cookie,数据存储

              当你想把这个类写的完善时,以上是你需要考虑的问题。

              (爬取新浪微博参考博客链接http://blog.csdn.net/memray/article/details/8876844)


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值