package regex.test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* 网页爬虫:其实就是一个程序用于在互联网中获取符合指定规则的数据
*
* 爬取网邮箱地址
*/
public class RegexTest2 {
public static void main(String[] args) throws IOException {
List<String>list=getMailsbyweb();
for(String mail:list) {
System.out.println(mail);
}
}
//爬取网上信息
private static List<String> getMailsbyweb() throws IOException {
URL url=new URL("http://my.yingjiesheng.com/xjh-000-776-746.html");
BufferedReader bufIn=new BufferedReader(new InputStreamReader(url.openStream()));
String mail_regex="[a-zA-Z]+@[a-zA-Z0-9]+(\\.[a-zA-Z]{1,3})+";
List<String> list=new ArrayList<String>();
Pattern p=Pattern.compile(mail_regex);
String line=null;
while((line=bufIn.readLine())!=null) {
Matcher m=p.matcher(line);
while(m.find()) {
list.add(m.group());
}
}
return list;
}
//爬取本地网页信息
public static List<String> getMails() throws IOException {
//1 读取源文件
BufferedReader bufr=new BufferedReader(new FileReader("1.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()) {
list.add(m.group());
}
}
return list;
//2 对读取的数据进行规则的匹配 从中获取符合规则的数据
//3将符合规则的数据储存到集合中
}
}
java 简单爬虫练习
最新推荐文章于 2023-07-25 17:49:11 发布