Java爬蟲
一、代碼
爬蟲的實質就是打開網頁源代碼進行匹配查找,然后獲取查找到的結果。
打開網頁:
1
|
URL url = new URL(http: //www.cnblogs.com/Renyi-Fan/p/6896901.html); |
讀取網頁內容:
1
|
BufferedReader bufr = new BufferedReader( new InputStreamReader(url.openStream())); |
正則表達式進行匹配:
1
|
tring mail_regex = "\\w+@\\w+(\\.\\w+)+" ; |
儲存結果:
1
|
List<String> list = new ArrayList<String>(); |
/*
* 獲取
* 將正則規則進行對象的封裝。
* Pattern p = Pattern.compile("a*b");
* //通過正則對象的matcher方法字符串相關聯。獲取要對字符串操作的匹配器對象Matcher .
* Matcher m = p.matcher("aaaaab");
* //通過Matcher匹配器對象的方法對字符串進行操作。
* boolean b = m.matches();
*/
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
|
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Spider { public static void main(String[] args) throws IOException { // List<String> list = getMails(); // for(String mail : list){ // System.out.println(mail); // } List<String> list = getMailsByWeb(); for (String mail : list){ System.out.println(mail); } } public static List<String> getMailsByWeb() throws IOException{ //1,讀取源文件。 //URL url = new URL("http://192.168.1.100:8080/myweb/mail.html"); //URL url = new URL("http://localhost:8080/SecondWeb/index.jsp"); URL url = new URL( "http://www.cnblogs.com/Renyi-Fan/p/6896901.html" ); BufferedReader bufr = new BufferedReader( new InputStreamReader(url.openStream())); //2,對讀取的數據進行規則的匹配。從中獲取符合規則的數據. String mail_regex = "\\w+@\\w+(\\.\\w+)+" ; List<String> list = new ArrayList<String>(); Pattern p = Pattern.compile(mail_regex); String line = null ; while ((line=bufr.readLine())!= null ){ Matcher m = p.matcher(line); while (m.find()){ //3,將符合規則的數據存儲到集合中。 list.add(m.group()); } } return list; } public static List<String> getMails() throws IOException{ //1,讀取源文件。 BufferedReader bufr = new BufferedReader( new FileReader( "c:\\mail.html" )); //2,對讀取的數據進行規則的匹配。從中獲取符合規則的數據. String mail_regex = "\\w+@\\w+(\\.\\w+)+" ; List<String> list = new ArrayList<String>(); Pattern p = Pattern.compile(mail_regex); String line = null ; while ((line=bufr.readLine())!= null ){ Matcher m = p.matcher(line); while (m.find()){ //3,將符合規則的數據存儲到集合中。 list.add(m.group()); } } return list; } } |
二、運行結果
1
2
|
abc1 @sina .com.cn 1 @1 .1 |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://www.cnblogs.com/Renyi-Fan/p/6897023.html