這是我參考了網上一些資料寫的第一個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();}} }