Java簡單爬蟲樣本__Java

來源:互聯網
上載者:User

步驟簡介

開啟連結:URL類初始化給定網頁連結,並調用openConnection()返回一個HttpURLConnection類的父類URLConnection執行個體。 擷取連結常值內容:URLConnection執行個體調用getInputStream()擷取輸入資料流,並返回輸入資料流(InputStream)對象,初始化給InputStreamReader,將位元組流轉換為字元流,並指定字元集編碼UTF-8。BufferedReader從字元流中逐行讀取文本存入String類型。 匹配圖片連結:Pattern調用compile(String url)將給定的Regex編譯,把編譯後的表現模式並賦予給Pattern類的執行個體p,用p.matcher()方法來產生一個Matcher執行個體m,接著使用該Matcher執行個體對目標字串進行匹配。m.find()尋找下一個子串,m.group()與組匹配的子串內容。 查重:Set集合來判斷尋找到的子串是否重複,如果不重複則添加到集合裡。 讀取輸入資料流:URL類初始化給定尋找到的圖片連結,並調用openConnection()返回一個HttpURLConnection的執行個體,用這個執行個體調用getInputStream()擷取輸入資料流,並初始化給緩衝輸入資料流BufferedInputStream。 寫入輸出資料流:建立ByteArrayOutputStream執行個體和byte數組執行個體,用BufferedInputStream讀入到byte數組裡,並緩衝到位元組數組輸出資料流。 儲存圖片資料:FileOutputStream(String name)建立向指定名稱的檔案中寫入資料的輸出檔案流,並初始化到輸出資料流,然後將位元組數組中的資料通過OutputStream寫入指定位置。 關閉流:對以上的輸入輸出資料流的關閉close();


程式碼範例

Set<String> imageUrlSet = new HashSet<String>();URLConnection urlconn;try { for (int i = 1; i <= 35; i++) { Thread.sleep(4000); String url = "http://www.iconarchive.com/show/ios7-icons-by-icons8." + i + ".html"; System.err.println("\r\nStart to crawl: " + url); urlconn = new URL(url).openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "utf-8")); String line = null;String src = "";while ((line = reader.readLine()) != null) {src += line;}// System.out.println(src); Pattern p = Pattern.compile("http://icons.iconarchive.com/icons/icons8/ios7/128/.+?.png");Matcher m = p.matcher(src);while (m.find()) {String imageUrl = m.group();                        if(imageUrlSet.contains(imageUrl)){continue;}imageUrlSet.add(imageUrl); urlconn = new URL(imageUrl).openConnection();BufferedInputStream inStream = new BufferedInputStream(urlconn.getInputStream()); ByteArrayOutputStream bOutStream = new ByteArrayOutputStream(); byte[] buf = new byte[1024];int size = 0;while ((size = inStream.read(buf)) > 0) {bOutStream.write(buf, 0, size);} byte[] srcBin = bOutStream.toByteArray(); String fileName = imageUrl.replaceAll("^.+/", "");System.out.print(fileName+"\t"); OutputStream osr = new BufferedOutputStream(new FileOutputStream("ios7/" + fileName)); osr.write(srcBin); inStream.close();bOutStream.close();osr.close();}} } catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.