java爬取網頁資料

來源:互聯網
上載者:User

標籤:開頭   except   write   attr   爬取網頁   amr   parse   gpo   總結   

最近使用java實現了一個簡單的網頁資料抓取,下面是實現原理及實現代碼:

原理:使用java.net下面的URL對象擷取一個連結,下載目標網頁的原始碼,利用jsoup解析原始碼中的資料,擷取你想要的內容

1.首先是根據網址下載原始碼:

/**     * 根據網址和編碼下載原始碼     * @param url 目標網址     * @param encoding 編碼     * @return     */    public static String getHtmlResourceByURL(String url,String encoding){                //儲存原始碼容器        StringBuffer buffer = new StringBuffer();        URL urlObj = null;        URLConnection uc = null;        InputStreamReader isr = null;        BufferedReader br =null;        try {            //建立網路連接            urlObj = new URL(url);            //開啟網路連接            uc = urlObj.openConnection();            //建立檔案輸入資料流            isr = new InputStreamReader(uc.getInputStream(),encoding);            InputStream is = uc.getInputStream();            //建立檔案緩衝寫入流            br = new BufferedReader(isr);            FileOutputStream fos = new FileOutputStream("F:\\java-study\\downImg\\index.txt");                        //建立臨時變數            String temp = null;            while((temp = br.readLine()) != null){                buffer.append(temp + "\n");            }//            fos.write(buffer.toString().getBytes());//            fos.close();        } catch (MalformedURLException e) {            e.printStackTrace();            System.out.println("網路不給力,請檢查網路設定。。。。");        }catch (IOException e){            e.printStackTrace();            System.out.println("你的網路連接開啟失敗,請稍後重新嘗試!");        }finally {            try {                isr.close();            } catch (IOException e) {                e.printStackTrace();            }        }                return buffer.toString();    }

2.根據下載原始碼解析資料,擷取你想要的內容,這裡我擷取的是圖片,你也可以擷取貼吧裡郵箱,電話號碼等

/**     * 擷取圖片路勁     * @param url 網路路徑     * @param encoding 編碼     */    public static void downImg(String url,String encoding){        String resourceByURL = getHtmlResourceByURL(url, encoding);        //2.解析原始碼,根據網狀圖像地址,下載到伺服器        Document document = Jsoup.parse(resourceByURL);                //擷取頁面中所有的圖片標籤        Elements elements = document.getElementsByTag("img");                for(Element element:elements){            //擷取映像地址            String src = element.attr("src");            //包含http開頭            if (src.startsWith("http") && src.indexOf("jpg") != -1) {                getImg(src, "F:\\java-study\\downImg");            }        }    }

3.根據擷取的圖片路徑,下載圖片,這裡我下載的是攜程網的內容

/**     * 下載圖片     * @param imgUrl 圖片地址     * @param filePath 儲存路勁     *      */    public static void getImg(String imgUrl,String filePath){                String fileName = imgUrl.substring(imgUrl.lastIndexOf("/"));                try {            //建立目錄            File files = new File(filePath);            if (!files.exists()) {                files.mkdirs();            }            //擷取地址            URL url = new URL(imgUrl);            //開啟串連            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            //擷取輸入資料流            InputStream is = connection.getInputStream();            File file = new File(filePath + fileName);            //建立問價輸入資料流            FileOutputStream fos = new FileOutputStream(file);                        int temp = 0;            while((temp = is.read()) != -1){                fos.write(temp);            }            is.close();            fos.close();        } catch (Exception e) {            e.printStackTrace();        }    }

最後是調用過程

public static void main(String[] args) {                //1.根據網址和頁面編碼集擷取網頁原始碼        String encoding = "gbk";        String url = "http://vacations.ctrip.com/";        //2.解析原始碼,根據網狀圖像地址,下載到伺服器        downImg(url, encoding);            }

總結:根據上面的實現的簡單資料爬取,存在著一些問題,我爬取的旅遊頁面有很多圖片,根據img屬性擷取其src中的地址,從而下載該圖片,但是該頁面有很多圖片,結果自己卻只能爬到一小部分,如:

我將下載的原始碼寫入檔案,和原網頁中做對比,基本上頁面旅遊的圖片一張沒有,原始碼中也沒有,不知道為什麼,請求廣大網友的解答

java爬取網頁資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.