转载自:http://blog.csdn.net/xyang81/article/details/7705960
实现思路:
1、使用java.net.URL对象,绑定网络上某一个网页的地址
2、通过java.net.URL对象的openConnection()方法获得一个HttpConnection对象
3、通过HttpConnection对象的getInputStream()方法获得该网络文件的输入流对象InputStream
4、循环读取流中的每一行数据,并由Pattern对象编译的正则表达式区配每一行字符,取得email地址
- package regex;
- 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;
- /**
- * 网络爬虫,抓取网页中的email地址
- */
- public class WebCrawlersDemo {
- public static void main(String[] args) throws Exception {
- URL url = new URL("http://www.tianya.cn/publicforum/content/english/1/129176.shtml");
- // 打开连接
- URLConnection conn = url.openConnection();
- // 设置连接网络超时时间
- conn.setConnectTimeout(1000 * 10);
- // 读取指定网络地址中的文件
- BufferedReader bufr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line = null;
- String regex = "[a-zA-Z0-9_-]+@\\w+\\.[a-z]+(\\.[a-z]+)?"; // 匹配email的正则
- Pattern p = Pattern.compile(regex);
- while((line = bufr.readLine()) != null) {
- Matcher m = p.matcher(line);
- while(m.find()) {
- System.out.println(m.group());<span style="white-space:pre"> </span>// 获得匹配的email
- }
- }
- }
- }