饭饭_fan 通过本文主要向大家介绍了java网络爬虫实例,java爬虫实例,网络爬虫java,java爬虫代码,网络爬虫代码 java等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
Java爬虫
一、代码
爬虫的实质就是打开网页源代码进行匹配查找,然后获取查找到的结果。
打开网页:
URL url = new URL(http://www.cnblogs.com/Renyi-Fan/p/6896901.html);</div>
读取网页内容:
BufferedReader bufr = new BufferedReader(new InputStreamReader(url.openStream()));</div>
正则表达式进行匹配:
tring mail_regex = "\\w+@\\w+(\\.\\w+)+";</div>
储存结果:
List<String> list = new ArrayList<String>();</div>
/*
* 获取
* 将正则规则进行对象的封装。
* Pattern p = Pattern.compile("a*b");
* //通过正则对象的matcher方法字符串相关联。获取要对字符串操作的匹配器对象Matcher .
* Matcher m = p.matcher("aaaaab");
* //通过Matcher匹配器对象的方法对字符串进行操作。
* boolean b = m.matches();
*/
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;
}
}
</div>
二、运行结果
abc1@sina.com.cn 1@1.1</div>
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
</div>
