爬虫:爬取其他网页内容到自己网站的操作。
方式一:httpclent
需要导入commons-logging ,httpclient ,httpcore 三个jar包
关键代码
//1.创建HttpClientBuilder对象
HttpClientBuilder builder = HttpClients.customs();
//2.创建httpClient对象
CloseableHttpClient hc = builder.bduild();
//摸弄get请求
String url ="www.baidu.com";
HttpGet get = new HttpGet(url);
//执行请求
CloseableHttpResponse response = hc.execuet(get);
//请响应对象response中的实体内容取出
HttpEntity entity = response.getEntity();
//通过实体工具类转换成字符
String html = EntityUtils.toString(entity,"utf-8");
System.out.println("百度内容:"+html);
方式二:Jsoup
需要引入jar包Jsoup
String html = Jsoup.connect(url).get().html();
System.out.println("百度内容:"+html);
Jsoup和HttpClient的主要区别在于Jsoup使用起来更加简洁,不用记很多api方法,内部已经封装了httpclient的方法。同时还提供选择器可以快速定位页面元素的位置。选择器可以通过tag标签和class以及id的值去定位要爬取的元素位置