这是一个简单的网页爬虫程序。其主要功能是获取指定网页中的邮箱地址。
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.URL;import java.net.URLConnection;import java.util.HashSet;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;public class NetSpider {public static void main(String[] args) throws IOException {String str_url = "https://bbs.hcbbs.com/thread-1259140-1-1.html";// 提供网络地址的URLString regex = "\w+@\w+(\.\w+)+";// 匹配规则(使用正则表达式)(这个匹配邮箱的正则表达式只是一个宽泛的匹配模式)SetString set = getMailsByNet(str_url, regex);// getMailsByNet(str_url,regex)方法返回获得的邮件地址for (String string : set) {// 遍历set集合,打印遍历到的邮箱地址System.out.println(string);}}// 基于网络的获取邮件地址public static SetString getMailsByNet(String str_url, String regex)throws IOException {SetString set = new HashSetString();// 创建list集合URL url = new URL(str_url);// 将str_url封装成URL对象URLConnection conn = url.openConnection();// 打开连接InputStream in = conn.getInputStream();// 获取读取流BufferedReader bufIn = new BufferedReader(new InputStreamReader(in));Pattern p = Pattern.compile(regex);// 将正则表达式编译成对象String line = null;// 频繁读写操作while ((line = bufIn.readLine()) != null) {Matcher m = p.matcher(line);// 通过正则表达式对象获取匹配器while (m.find()) {// 把得到的邮箱存储到list集合中set.add(m.group());}}bufIn.close();// 关闭资源return set;}}小程序













