【初學】java爬蟲並抓取圖片儲存

來源:互聯網
上載者:User

這是我參考了網上一些資料寫的第一個java爬蟲程式

本來是想擷取煎蛋網無聊圖的圖片,但是網路返回碼一直是503,所以換了網站


/* * 網路爬蟲取資料 *  * */public class JianDan {public static String GetUrl(String inUrl){StringBuilder sb = new StringBuilder();try {URL url =new URL(inUrl);BufferedReader reader =new BufferedReader(new InputStreamReader(url.openStream()));String temp="";while((temp=reader.readLine())!=null){//System.out.println(temp);sb.append(temp);}} catch (MalformedURLException e) {// TODO 自動產生的 catch 塊e.printStackTrace();} catch (IOException e) {// TODO 自動產生的 catch 塊e.printStackTrace();}return sb.toString();}public static List<String> GetMatcher(String str,String url){List<String> result = new ArrayList<String>();Pattern p =Pattern.compile(url);//擷取網頁地址Matcher m =p.matcher(str);while(m.find()){//System.out.println(m.group(1));result.add(m.group(1));}return result;}public static void main(String args[]){String str=GetUrl("http://www.163.com");List<String> ouput =GetMatcher(str,"src=\"([\\w\\s./:]+?)\"");for(String temp:ouput){//System.out.println(ouput.get(0));System.out.println(temp);}String aurl=ouput.get(0); // 構造URLURL url;try {url = new URL(aurl); // 開啟URL串連URLConnection con = (URLConnection)url.openConnection(); // 得到URL的輸入資料流InputStream input = con.getInputStream();// 設定資料緩衝byte[] bs = new byte[1024 * 2];// 讀取到的資料長度int len;// 輸出的檔案流儲存圖片至本地OutputStream os = new FileOutputStream("a.png");while ((len = input.read(bs)) != -1) {os.write(bs, 0, len);}os.close();input.close();} catch (MalformedURLException e) {// TODO 自動產生的 catch 塊e.printStackTrace();} catch (IOException e) {// TODO 自動產生的 catch 塊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.