【初学】java爬虫并抓取图片保存

来源:互联网 发布:网络诈骗的例子 编辑:程序博客网 时间:2024/04/19 15:36

这是我参考了网上一些资料写的第一个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();}} }


2 0
原创粉丝点击