近期在做数据抓取功能,抓取到的数据为html格式,需在后台进行转换后取值,为了避免使用字符串查找方式获取而使用Jsonp完美实现。
1. 引入Jsonp:
11 <dependency> 22 <groupId>org.jsoup</groupId> 33 <artifactId>jsoup</artifactId> 44 <version>1.11.2</version> 55 </dependency>
2. 进行数据转换:
2.1 select可以获取HTML标签,类型为Elements;
2.2 child(int index) 可以根据坐标获取子标签;
2.3 text()可以获取便签内容。
1 1 // 解析返回数据 2 2 try { 3 3 Document doc = Jsoup.parse(result); 4 4 // 获取响应内容指定区域标签 5 5 Elements elements = doc.select(".BOC_main").select("tr"); 6 6 // 获取具体值 7 7 text = elements.get(1).child(6).text(); 8 8 } catch(Exception e) { 9 9 e.printStackTrace(); 1010 }
3. 抓取数据方法:
其中,请求属性要根据实际情况修改。
1private static String getUrlInfo(String url, String methodType, String param){ 2 try { 3 URL url = new URL(urls); 4 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 5 // 设置连接超时时间 6 conn.setConnectTimeout(60000); 7 // 设置读取超时时间 8 conn.setReadTimeout(60000); 9 10 if("Get".equalsIgnoreCase(methodType)) { 11 conn.setRequestMethod("GET"); 12 }else { 13 conn.setRequestMethod("POST"); 14 } 15 16 // 设置请求属性 17 conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); 18 conn.setRequestProperty("Connection", "keep-alive"); 19 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 20 conn.setRequestProperty("Host", "host"); 21 22 conn.setDoInput(true); 23 conn.setDoOutput(true); 24 // 设置是否使用缓存 25 conn.setUseCaches(false); 26 27 if(StringUtil.isNotBlank(param)) { 28 // 建立输入流,向指向的URL传入参数 29 DataOutputStream dos=new DataOutputStream(conn.getOutputStream()); 30 dos.writeBytes(param); 31 dos.flush(); 32 dos.close(); 33 } 34 35 // 输出返回结果 36 InputStream input = conn.getInputStream(); 37 int resLen =0; 38 byte[] res = new byte[1024]; 39 StringBuilder sb=new StringBuilder(); 40 while((resLen=input.read(res))!=-1){ 41 sb.append(new String(res, 0, resLen)); 42 } 43 return sb.toString(); 44 } catch (MalformedURLException e) { 45 e.printStackTrace(); 46 } catch (IOException e) { 47 e.printStackTrace(); 48 } 49 return ""; 50}