java爬蟲簡單一實例

來源:互聯網
上載者:User

標籤:put   row   out   讀取   mpi   reader   return   com   fan   

爬蟲的實質就是開啟網頁原始碼進行匹配尋找,然後擷取尋找到的結果。
/*
* 擷取
* 將正則規則進行對象的封裝。 
* Pattern p = Pattern.compile("a*b");
* //通過正則對象的matcher方法字串相關聯。擷取要對字串操作的匹配器對象Matcher .
* Matcher m = p.matcher("aaaaab");
* //通過Matcher匹配器對象的方法對字串進行操作。
* boolean b = m.matches();
*/
package com.js.ai.modules.pointwall.testxfz;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.MalformedURLException;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 List<String> getMailsByWeb() throws IOException{//1,讀取源檔案。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 = "\\[email protected]\\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 = "\\[email protected]\\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 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);}}}

  

java爬蟲簡單一實例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.