本文实例讲述了java实现的爬虫抓取图片并保存操作。分享给大家供大家参考,具体如下:
这是我参考了网上一些资料写的第一个java爬虫程序
本来是想获取煎蛋网无聊图的图片,但是网络返回码一直是503,所以换了网站
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
import java.io.bufferedreader; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.outputstream; import java.net.malformedurlexception; import java.net.url; import java.net.urlconnection; import java.util.arraylist; import java.util.list; import java.util.regex.matcher; import java.util.regex.pattern; /* * 网络爬虫取数据 * * */ 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 ); // 构造url url 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(); } } } |
运行输出:
希望本文所述对大家java程序设计有所帮助。
原文链接:https://blog.csdn.net/smilecjw/article/details/52423378
查看更多关于Java实现的爬虫抓取图片并保存操作示例的详细内容...