现实生活中咱们常常在浏览网页时看到自己需要的信息,但由于信息过于庞大而又不能逐个保存下来。

接下来,咱们就以获取邮箱地址为例,使用java语言抓取网页中的邮箱地址

实现思路如下:

1、使用Java.net.URL对象,绑定网络上某一个网页的地址

2、通过java.net.URL对象的openConnection()方法获得一个URLConnection对象

3、通过URLConnection对象的getInputStream()方法获得该网络文件的输入流对象InputStream

4、循环读取流中的每一行数据,并由Pattern对象编译的正则表达式区配每一行字符,取得email地址

接下来,话不多说,直接上代码:

import java.io.BufferedReader;  
import java.io.InputStreamReader;  
import java.net.URL;  
import java.net.URLConnection;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;   
public class Test {  
      
    public static void main(String[] args) throws Exception {  
     //设定目标网址        
     URL url = new URL("目标网址");  
        // 打开连接  
        URLConnection conn = url.openConnection();  
        // 设置连接网络超时时间  
        conn.setConnectTimeout(1000 * 10);  
        // 读取指定网络地址中的文件  
        BufferedReader bufr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     //在内存中构建一个空的字符串来准备获取读到的邮箱  
        String line = null;  
     // 设置匹配email的正则表达式;  

        String reg = "[a-zA-Z0-9_-]+@\\w+\\.[a-z]+(\\.[a-z]+)?"; 
        Pattern p = Pattern.compile(reg); 
     //循环输出读到的邮箱地址
        while((line = bufr.readLine()) != null) {  
            Matcher m = p.matcher(line);  
            while(m.find()) {  
                System.out.println(m.group());
            }  
        }  
    }  
  
}

本人水平有限,不能详尽解读以上代码,还望见谅