前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >利用Jsoup扒取百度图片

利用Jsoup扒取百度图片

作者头像
林老师带你学编程
发布2018-01-04 10:48:40
1.5K0
发布2018-01-04 10:48:40
举报
文章被收录于专栏:强仔仔强仔仔

因为业务的需求,需要去百度图片搜索中搜索相应的图片,但是得批量完成,因为人工搜索图片效率太低,所以只能通过扒取网页的形式,扒取图片。然后将图片存储在本地的文件下面。

下面我将用Jsoup来扒取百度图片,并通过java中io保存在本地文件中。

步骤大致可以分为三个模块:一是获取网页的资源,二是解析获取的资源,取出我们想要的图片URL地址,三是通过java的io存储在本地文件中。

获取网页资源的核心模块就是通过Jsoup去获取网页的内容,具体核心代码如下:

代码语言:javascript
复制
 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地址是百度图片搜索的地址,具体调用代码如下:

代码语言:javascript
复制
    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是一页显示多少个数据。

解析网页的资源,然后封装起来。核心代码如下:

代码语言:javascript
复制
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流去图片地址获取图片,并保存在本地。核心代码如下:

代码语言:javascript
复制
 //根据图片网络地址下载图片
    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咨询

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年11月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档