java编写爬虫入门

       获取互联网中特定的数据,爬虫是主要的方法之一。本文主要是用java编写爬虫,用到的技术有HttpCilent通过http协议对互联网进行访问,得到document对象和Jsoupdocument进行解析,获得想要的数据。主要实现了get方法的获取和解析。

     httpClient访问互联网主要步骤为:

    1.创建默认客户端对象

    2.创建get方法对象

    3.客户端执行get方法对象,获得相应数据

    4.用EntityUtils处理相应结果,成为String类型

    5.用Jsoup对得到的String字符串进行解析

    6.得到document对象,对document对象中数据进行提取获得想要的数据

   示例代码:

 
 
package httpclient;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Get {
     public static void main(String[] args) throws Exception, IOException {
		 //1.创建客户端 
    	 CloseableHttpClient httpClient = HttpClients.createDefault();
    	 //2.创建get请求
    	 HttpGet httpGet = new HttpGet("https://www.csdn.net");
    	 //3.执行get请求,得到响应
    	 CloseableHttpResponse response = httpClient.execute(httpGet);
    	 //4.判断是否响应成功=状态码为200
    	 if(response.getStatusLine().getStatusCode()==200){
    		 //5.获得响应结果
    		 HttpEntity entity = response.getEntity();
    		 String html = EntityUtils.toString(entity,Charset.forName("utf-8"));
    		 //System.out.println(html);
    		 //6.关闭响应
    		 //使用jsoup解析得到的数据 
    		 //6.1得到document对象
    		 Document document = Jsoup.parse(html);
    		 //6.2解析数据
    		 String title = document.title();
    		 System.out.println(title);
    		 //6.3提取所有链接
    		 Elements links = document.select("a[href]");  
    		    for (Element link : links) 
    		    {
    		         System.out.println("link : " + link.attr("href"));  
    		         System.out.println("text : " + link.text());  
    		    }
    		 response.close();
    	 }
	}
}

代码部分结果:



猜你喜欢

转载自blog.csdn.net/weixin_38000711/article/details/80512880
今日推荐