httpclient和jsoup

httpclient可以用get和post方法访问网页并返回相应内容,然后在jsoup上对返回的内容作处理再显示在客户端上可以达到预期的效果。


post方法:

//post方法
	public int post_http(String url,List<NameValuePair> params,HttpClient client) throws ClientProtocolException, IOException{
		HttpPost post=new HttpPost(url);
		HttpResponse response;
		post.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); 
		post.setEntity(new UrlEncodedFormEntity(params, "gb2312"));
		response=client.execute(post);
		post.abort();

		if(response.getFirstHeader("Location")==null){
			return 0;
		}else{
			return 1;
		}
		
	}

post提交的数据:

List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("__VIEWSTATE", zhuangtai));
		params.add(new BasicNameValuePair("tbYHM", id));
		params.add(new BasicNameValuePair("tbPSW", pwd));
		params.add(new BasicNameValuePair("ddlSF", "学生"));
		params.add(new BasicNameValuePair("imgDL.x", "27"));
		params.add(new BasicNameValuePair("imgDL.y", "11"));

httpclient会自动处理cookie等相关认证问题,只要使用同一个client就可以保持通讯。如:

HttpClient client_jiaowu=new DefaultHttpClient();

get方法:

//get方法
	public String get_http(String url,HttpClient client){
		String wangyeneirong = null;  //保存网页内容
		HttpResponse httpResponse;    //建立响应
		HttpGet get = new HttpGet(url);    //建立get
		try {
			httpResponse = client.execute(get);  //执行

			HttpEntity entity = httpResponse.getEntity();  
			wangyeneirong=EntityUtils.toString(entity);  
			get.abort(); //关闭连接
			
			return wangyeneirong;
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		return null;
	}

使用httpclient常见的问题:

一、例如登录一个网站的时候,提交了所有的数据依然还是无法正确登陆。

把所有的input标签里的内容都提交是一个办法,因为站点有设置__VIEWSTATE,或类似的状态码,总之有些页面是需要先取得状态码然后再提交才能正确登录的。

二、设置相应的头信息。

用httpwatch抓取正常访问时提交的数据,除了正确的提交各个参数外,有些站点会验证是否是浏览器访问,这时需要设置和httpwatch抓取的信息相应的头信息,如:

HttpGet get = new HttpGet(tushuguan);    //建立get
		get.setHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		get.setHeader("Host","210.38.32.201");
		get.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		get.setHeader("Accept-Encoding","gzip,deflate,sdch");
		get.setHeader("Accept-Language","zh-CN,zh;q=0.8");
		get.setHeader("Cache-Control","max-age=0");
		get.setHeader("Connection","keep-alive");

使用jsoup的常见问题:

jsoup不难使用,通过Jsoup.parse方法把文本载入doc,或Jsoup.connect方法直接访问链接获得页面内容并载入doc(对于一些复杂的页面不一定成功)。然后再对doc的内容进行筛选即可(当然这只是初级用法)。


select选择器:

方法Element.select(String selector)Elements.select(String selector)

选择器概要(Selector overview)

  • Tagname:通过标签查找元素(例如:a)
  • ns|tag:通过标签在命名空间查找元素,例如:fb|name查找<fb:name>元素
  • #id:通过ID查找元素,例如#logo
  • .class:通过类型名称查找元素,例如.masthead
  • [attribute]:带有属性的元素,例如[href]
  • [^attr]:带有名称前缀的元素,例如[^data-]查找HTML5带有数据集(dataset)属性的元素
  • [attr=value]:带有属性值的元素,例如[width=500]
  • [attr^=value],[attr$=value],[attr*=value]:包含属性且其值以value开头、结尾或包含value的元素,例如[href*=/path/]
  • [attr~=regex]:属性值满足正则表达式的元素,例如img[src~=(?i)\.(png|jpe?g)]
  • *:所有元素,例如*

选择器组合方法

  • el#id::带有ID的元素ID,例如div#logo
  • el.class:带类型的元素,例如. div.masthead
  • el[attr]:包含属性的元素,例如a[href]
  • 任意组合:例如a[href].highlight
  • ancestor child:继承自某祖(父)元素的子元素,例如.body p查找“body”块下的p元素
  • parent > child:直接为父元素后代的子元素,例如: div.content > pf查找p元素,body > * 查找body元素的直系子元素
  • siblingA + siblingB:查找由同级元素A前导的同级元素,例如div.head + div
  • siblingA ~ siblingX:查找同级元素A前导的同级元素X例如h1 ~ p
  • el, el, el:多个选择器组合,查找匹配任一选择器的唯一元素,例如div.masthead, div.logo

伪选择器(Pseudo selectors)

  • :lt(n):查找索引值(即DOM树中相对于其父元素的位置)小于n的同级元素,例如td:lt(3)
  • :gt(n):查找查找索引值大于n的同级元素,例如div p:gt(2)
  • :eq(n) :查找索引值等于n的同级元素,例如form input:eq(1)
  • :has(seletor):查找匹配选择器包含元素的元素,例如div:has(p)
  • :not(selector):查找不匹配选择器的元素,例如div:not(.logo)
  • :contains(text):查找包含给定文本的元素,大小写铭感,例如p:contains(jsoup)
  • :containsOwn(text):查找直接包含给定文本的元素
  • :matches(regex):查找其文本匹配指定的正则表达式的元素,例如div:matches((?i)login)
  • :matchesOwn(regex):查找其自身文本匹配指定的正则表达式的元素
  • 注意:上述伪选择器是0-基数的,亦即第一个元素索引值为0,第二个元素index为1等

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Jsoup+httpclient 模拟登陆和抓取页面 package com.app.html; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.app.comom.FileUtil; public class HttpClientHtml { private static final String SITE = "login.goodjobs.cn"; private static final int PORT = 80; private static final String loginAction = "/index.php/action/UserLogin"; private static final String forwardURL = "http://user.goodjobs.cn/dispatcher.php/module/Personal/?skip_fill=1"; private static final String toUrl = "d:\\test\\"; private static final String css = "http://user.goodjobs.cn/personal.css"; private static final String Img = "http://user.goodjobs.cn/images"; private static final String _JS = "http://user.goodjobs.cn/scripts/fValidate/fValidate.one.js"; /** * 模拟等录 * @param LOGON_SITE * @param LOGON_PORT * @param login_Action * @param params * @throws Exception */ private static HttpClient loginHtml(String LOGON_SITE, int LOGON_PORT,String login_Action,String ...params) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); // 模拟登录页面 PostMethod post = new PostMethod(login_Action); NameValuePair userName = new NameValuePair("memberName",params[0] ); NameValuePair password = new NameValuePair("password",params[1] ); post.setRequestBody(new NameValuePair[] { userName, password }); client.executeMethod(post); post.releaseConnection(); // 查看cookie信息 CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); if (cookies != null) if (cookies.length == 0) { System.out.println("Cookies is not Exists "); } else { for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].toString()); } } return client; } /** * 模拟等录 后获取所需要的页面 * @param client * @param newUrl * @throws Exception */ private static String createHtml(HttpClient client, String newUrl) throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String filePath = toUrl + format.format(new Date() )+ "_" + 1 + ".html"; PostMethod post = new PostMethod(newUrl); client.executeMethod(post); //设置编码 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK"); String content= post.getResponseBodyAsString(); FileUtil.write(content, filePath); System.out.println("\n写入文件成功!"); post.releaseConnection(); return filePath; } /** * 解析html代码 * @param filePath * @param random * @return */ private static String JsoupFile(String filePath, int random) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); File infile = new File(filePath); String url = toUrl + format.format(new Date()) + "_new_" + random+ ".html"; try { File outFile = new File(url); Document doc = Jsoup.parse(infile, "GBK"); String html="<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"; StringBuffer sb = new StringBuffer(); sb.append(html).append("\n"); sb.append("<html>").append("\n"); sb.append("<head>").append("\n"); sb.append("<title>欢迎使用新安人才网个人专区</title>").append("\n"); Elements meta = doc.getElementsByTag("meta"); sb.append(meta.toString()).append("\n"); ////////////////////////////body////////////////////////// Elements body = doc.getElementsByTag("body"); ////////////////////////////link////////////////////////// Elements links = doc.select("link");//对link标签有href的路径都作处理 for (Element link : links) { String hrefAttr = link.attr("href"); if (hrefAttr.contains("/personal.css")) { hrefAttr = hrefAttr.replace("/personal.css",css); Element hrefVal=link.attr("href", hrefAttr);//修改href的属性值 sb.append(hrefVal.toString()).append("\n"); } } ////////////////////////////script////////////////////////// Elements scripts = doc.select("script");//对script标签 for (Element js : scripts) { String jsrc = js.attr("src"); if (jsrc.contains("/fValidate.one.js")) { String oldJS="/scripts/fValidate/fValidate.one.js";//之前的css jsrc = jsrc.replace(oldJS,_JS); Element val=js.attr("src", jsrc);//修改href的属性值 sb.append(val.toString()).append("\n").append("</head>"); } } ////////////////////////////script////////////////////////// Elements tags = body.select("*");//对所有标签有src的路径都作处理 for (Element tag : tags) { String src = tag.attr("src"); if (src.contains("/images")) { src = src.replace("/images",Img); tag.attr("src", src);//修改src的属性值 } } sb.append(body.toString()); sb.append("</html>"); BufferedReader in = new BufferedReader(new FileReader(infile)); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "gbk")); String content = sb.toString(); out.write(content); in.close(); System.out.println("页面已经爬完"); out.close(); } catch (IOException e) { e.printStackTrace(); } return url; } public static void main(String[] args) throws Exception { String [] params={"admin","admin123"}; HttpClient client = loginHtml(SITE, PORT, loginAction,params); // 访问所需的页面 String path=createHtml(client, forwardURL); System.out.println( JsoupFile(path,1)); } }
要使用Java编写基于HttpClientJsoup的爬虫,需要进行以下步骤: 1. 首先,导入HttpClientJsoup的依赖包。可以使用maven或gradle进行依赖管理。 2. 创建一个HttpClient实例,用于发送HTTP请求和接收响应。可以使用HttpClients.createDefault()方法创建一个默认配置的实例。 3. 创建一个HttpGet实例,设置请求URL和请求头信息。可以使用new HttpGet(url)方法创建一个HttpGet实例,然后使用setHeader()方法设置请求头信息。 4. 发送HTTP请求,并获取响应结果。可以使用HttpClient.execute()方法发送请求,并使用HttpResponse.getEntity()方法获取响应实体。 5. 解析HTML内容。可以使用Jsoup.parse()方法解析HTML内容,然后使用Jsoup提供的API进行内容提取和处理。 以下是一个使用HttpClientJsoup进行网页爬取的示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; public class WebCrawler { public static void main(String[] args) throws IOException { // 创建一个HttpClient实例 HttpClient httpClient = HttpClients.createDefault(); // 创建一个HttpGet实例,设置请求URL和请求头信息 HttpGet httpGet = new HttpGet("https://www.example.com"); httpGet.setHeader("User-Agent", "Mozilla/5.0"); // 发送HTTP请求,并获取响应结果 HttpResponse httpResponse = httpClient.execute(httpGet); String html = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); // 解析HTML内容 Document document = Jsoup.parse(html); String title = document.title(); System.out.println("Title: " + title); } } ``` 在这个示例中,我们使用HttpClient发送了一个GET请求到https://www.example.com,并获取了响应结果。然后使用Jsoup解析HTML内容,并获取了网页的标题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值