Java实现的爬虫抓取图片并保存操作示例

2025-05-29 0 49

本文实例讲述了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实现的爬虫抓取图片并保存操作示例

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/smilecjw/article/details/52423378

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java实现的爬虫抓取图片并保存操作示例 https://www.kuaiidc.com/111102.html

相关文章

发表评论
暂无评论