当前位置: 首页 > news >正文

爬虫小demo

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

运用apache httpclient爬数据、httpcleaner解析爬回来的数据:

package cn.sniper.spider.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
public class SpiderUtil {
 
 private String pageContent;
 
 @Before
 public void init() {
  HttpClientBuilder builder = HttpClients.custom();
  CloseableHttpClient client = builder.build();
  String url = "http://www.2345.com/";
  
  HttpGet request = new HttpGet(url);
  
  try {
   CloseableHttpResponse resp = client.execute(request);
   HttpEntity entity = resp.getEntity();
   pageContent = EntityUtils.toString(entity);
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 /**
  * 抓取整个页面
  */
 @Test
 public void testDownload1() {
  HttpClientBuilder builder = HttpClients.custom();
  CloseableHttpClient client = builder.build();
  String url = "http://www.2345.com/";
  
  HttpGet request = new HttpGet(url);
  
  try {
   CloseableHttpResponse resp = client.execute(request);
   HttpEntity entity = resp.getEntity();
   String pageContent = EntityUtils.toString(entity);
   System.out.println(pageContent);
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 /**
  * 取得text内容
  */
 @Test
 public void testDownload2() {
  HtmlCleaner cleaner = new HtmlCleaner();
  TagNode rootNode = cleaner.clean(pageContent);
  
  //拿到id=name元素中的第一个h1元素,如果只有一个,//*[@id=\"name\"]h1
  String xPathExpression = "//*[@id=\"name\"]h1[1]";
  
  try {
   Object[] objs = rootNode.evaluateXPath(xPathExpression);
   
   TagNode node = (TagNode)objs[0];
   System.out.println(node.getText());
  } catch (XPatherException e) {
   e.printStackTrace();
  }
  
 }
 
 /**
  * 通过属性名称取得值
  */
 @Test
 public void testDownload3() {
  HtmlCleaner cleaner = new HtmlCleaner();
  TagNode rootNode = cleaner.clean(pageContent);
  
  String xPathExpression = "//*[@id=\"j_search_img\"]";
  
  try {
   Object[] objs = rootNode.evaluateXPath(xPathExpression);
   
   TagNode node = (TagNode)objs[0];
   String src = node.getAttributeByName("src");
   
   //注意,需要写前缀:http:// 否则报错:java.net.MalformedURLException: no protocol
   URL url = new URL("http://www.2345.com/" + src);
   URLConnection conn = url.openConnection();
   InputStream is = conn.getInputStream();
   
   FileOutputStream fos = new FileOutputStream("D:/1.gif");
   
   int b = 0;
   while((b = is.read()) != -1) {
    fos.write(b);
   }
   
   fos.close();
   is.close();
   
   System.out.println(src);
  } catch (XPatherException e) {
   e.printStackTrace();
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
 
 /**
  * 抓取的页面返回json数据
  */
 @Test
 public void testDownload4() {
  HttpClientBuilder builder = HttpClients.custom();
  CloseableHttpClient client = builder.build();
  String url = "http://www.2345.com/";
  
  HttpGet request = new HttpGet(url);
  
  try {
   CloseableHttpResponse resp = client.execute(request);
   HttpEntity entity = resp.getEntity();
   String pageContent = EntityUtils.toString(entity);
   
   JSONArray jsonArray = new JSONArray(pageContent);
   JSONObject jsonObj = (JSONObject)jsonArray.get(0);
   System.out.println(jsonObj.get("price"));
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
}


转载于:https://my.oschina.net/sniperLi/blog/493786

相关文章:

  • Android学习路径(十)怎么会Action Bar堆放在布局
  • 论如何优雅的处理回文串 - 回文自动机详解
  • 按值传参,按引用传参,按指针传参的区别
  • linux 下Time_wait过多问题解决
  • SVN目录对号图标(更新、冲突)不显示
  • 神奇的make自动生成include file的功能
  • SLAM学习笔记(2)SLAM算法
  • Using MRR(Multi-Range Read )
  • BigMemroy系列文章--6. Ehcache扩展功能--Jmx、同步
  • Android的硬件抽象层模块编写规范
  • 第二次课总结笔记
  • Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name
  • SNMP常用数据操作
  • Provisioning Services 7.6 入门到精通系列之五:PVS控制台安装
  • matlab repmat()
  • 【腾讯Bugly干货分享】从0到1打造直播 App
  • angular学习第一篇-----环境搭建
  • AWS实战 - 利用IAM对S3做访问控制
  • exports和module.exports
  • javascript数组去重/查找/插入/删除
  • Java多线程(4):使用线程池执行定时任务
  • Java深入 - 深入理解Java集合
  • JS函数式编程 数组部分风格 ES6版
  • quasar-framework cnodejs社区
  • React组件设计模式(一)
  • vue脚手架vue-cli
  • 从零开始的无人驾驶 1
  • 翻译:Hystrix - How To Use
  • 观察者模式实现非直接耦合
  • 规范化安全开发 KOA 手脚架
  • 基于 Ueditor 的现代化编辑器 Neditor 1.5.4 发布
  • 理解 C# 泛型接口中的协变与逆变(抗变)
  • 力扣(LeetCode)22
  • 深入浅出webpack学习(1)--核心概念
  • 通过npm或yarn自动生成vue组件
  • 学习ES6 变量的解构赋值
  • 追踪解析 FutureTask 源码
  • Hibernate主键生成策略及选择
  • $(function(){})与(function($){....})(jQuery)的区别
  • (11)MSP430F5529 定时器B
  • (C语言)逆序输出字符串
  • (SpringBoot)第二章:Spring创建和使用
  • (WSI分类)WSI分类文献小综述 2024
  • (草履虫都可以看懂的)PyQt子窗口向主窗口传递参数,主窗口接收子窗口信号、参数。
  • (超详细)语音信号处理之特征提取
  • (多级缓存)多级缓存
  • (附源码)小程序 交通违法举报系统 毕业设计 242045
  • (论文阅读笔记)Network planning with deep reinforcement learning
  • (三)Pytorch快速搭建卷积神经网络模型实现手写数字识别(代码+详细注解)
  • (十二)devops持续集成开发——jenkins的全局工具配置之sonar qube环境安装及配置
  • (转)Linux NTP配置详解 (Network Time Protocol)
  • (转)shell中括号的特殊用法 linux if多条件判断
  • (转)自己动手搭建Nginx+memcache+xdebug+php运行环境绿色版 For windows版
  • **PyTorch月学习计划 - 第一周;第6-7天: 自动梯度(Autograd)**
  • ./indexer: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object fil