因为业务的需求,需要去百度图片搜索中搜索相应的图片,但是得批量完成,因为人工搜索图片效率太低,所以只能通过扒取网页的形式,扒取图片。然后将图片存储在本地的文件下面。
下面我将用Jsoup来扒取百度图片,并通过java中io保存在本地文件中。
步骤大致可以分为三个模块:一是获取网页的资源,二是解析获取的资源,取出我们想要的图片URL地址,三是通过java的io存储在本地文件中。
获取网页资源的核心模块就是通过Jsoup去获取网页的内容,具体核心代码如下:
private static List<JsoupImageVO> findImageNoURl(String hotelId, String url, int timeOut) { List<JsoupImageVO> result = new ArrayList<JsoupImageVO>(); Document document = null; try { document = Jsoup.connect(url).data("query", "Java")//请求参数 .userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")//设置urer-agent get(); .timeout(timeOut) .get(); String xmlSource = document.toString(); result = dealResult(xmlSource, hotelId); } catch (Exception e) { String defaultURL = "http://qnimg.zowoyoo.com/img/15463/1509533934407.jpg"; result = dealResult(defaultURL,hotelId); } return result; }
其中URL地址是百度图片搜索的地址,具体调用代码如下:
public static List<JsoupImageVO> findImage(String hotelName, String hotelId, int page) { int number=5; String url = "http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word=" + hotelName + "&cg=star&pn=" + page * 30 + "&rn="+number+"&itg=0&z=0&fr=&width=&height=&lm=-1&ic=0&s=0&st=-1&gsm=" + Integer.toHexString(page * 30); int timeOut = 5000; return findImageNoURl(hotelId, url, timeOut); }
这里需要注意的是:word是我们要搜索的关键字,pn是显示的页码,rn是一页显示多少个数据。
解析网页的资源,然后封装起来。核心代码如下:
private static List<JsoupImageVO> dealResult(String xmlSource, String hotelId) { List<JsoupImageVO> result = new ArrayList<JsoupImageVO>(); xmlSource = StringEscapeUtils.unescapeHtml3(xmlSource); String reg = "objURL\":\"http://.+?\\.(gif|jpeg|png|jpg|bmp)"; Pattern pattern = Pattern.compile(reg); Matcher m = pattern.matcher(xmlSource); while (m.find()) { JsoupImageVO jsoupImageVO = new JsoupImageVO(); String imageURL = m.group().substring(9); if(imageURL==null || "".equals(imageURL)){ String defaultURL = "http://qnimg.zowoyoo.com/img/15463/1509533934407.jpg"; jsoupImageVO.setUrl(defaultURL); }else{ jsoupImageVO.setUrl(imageURL); } jsoupImageVO.setName(hotelId); result.add(jsoupImageVO); } return result; }
这里最主要的地方就是reg这个正则表达式,通过正则表达式,去网页中解析符合规定的图片URL地址,然后封装在对象中。
最后一部分就是通过java的io流去图片地址获取图片,并保存在本地。核心代码如下:
//根据图片网络地址下载图片 public static void download(String url,String name,String path){ File file= null; File dirFile=null; FileOutputStream fos=null; HttpURLConnection httpCon = null; URLConnection con = null; URL urlObj=null; InputStream in =null; byte[] size = new byte[1024]; int num=0; try { dirFile = new File(path); if(dirFile.exists()){ dirFile.delete(); } dirFile.mkdir(); file = new File(path+"//"+name+".jpg"); fos = new FileOutputStream(file); if(url.startsWith("http")){ urlObj = new URL(url); con = urlObj.openConnection(); httpCon =(HttpURLConnection) con; in = httpCon.getInputStream(); while((num=in.read(size)) != -1){ for(int i=0;i<num;i++) fos.write(size[i]); } } }catch (FileNotFoundException notFoundE) { LogUtils.writeLog("找不到该网络图片...."); }catch(NullPointerException nullPointerE){ LogUtils.writeLog("找不到该网络图片...."); }catch(IOException ioE){ LogUtils.writeLog("产生IO异常....."); }catch (Exception e) { e.printStackTrace(); }finally{ try { fos.close(); } catch (Exception e) { e.printStackTrace(); } } }
这里面的操作都是java中io篇一些基础的操作,有不懂的可以去看看java中io模块的内容。
因为我这边是maven项目,所以在开发前需要引入Jsoup依赖才可以。
GitHub地址:https://github.com/1913045515/Jsoup/tree/master 大致的过程就是这样,如果对上面的内容还有什么疑义或者问题都可以加微信:qiang220316咨询
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句