網(wǎng)頁(yè)爬蟲(chóng):就是一個(gè)程序用于在互聯(lián)網(wǎng)中獲取指定規(guī)則的數(shù)據(jù)。
思路:
1.為模擬網(wǎng)頁(yè)爬蟲(chóng),我們可以現(xiàn)在我們的tomcat服務(wù)器端部署一個(gè)1.html網(wǎng)頁(yè)。(部署的步驟:在tomcat目錄的webapps目錄的ROOTS目錄下新建一個(gè)1.html。使用notepad++進(jìn)行編輯,編輯內(nèi)容為:
)
2.使用URL與網(wǎng)頁(yè)建立聯(lián)系
3.獲取輸入流,用于讀取網(wǎng)頁(yè)中的內(nèi)容
4.建立正則規(guī)則,因?yàn)檫@里我們是爬去網(wǎng)頁(yè)中的郵箱信息,所以建立匹配 郵箱的正則表達(dá)式:String regex=”w+@w+(.w+)+”;
5.將提取到的數(shù)據(jù)放到集合中。
代碼:
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * 網(wǎng)頁(yè)爬蟲(chóng):就是一個(gè)程序用于在互聯(lián)網(wǎng)中獲取指定規(guī)則的數(shù)據(jù) * * */ public class RegexDemo { public static void main(String[] args) throws Exception { List<String> list=getMailByWeb(); for(String str:list){ System.out.println(str); } } private static List<String> getMailByWeb() throws Exception { //1.與網(wǎng)頁(yè)建立聯(lián)系。使用URL String path="http://localhost:8080//1.html";//后面寫(xiě)雙斜杠是用于轉(zhuǎn)義 URL url=new URL(path); //2.獲取輸入流 InputStream is=url.openStream(); //加緩沖 BufferedReader br=new BufferedReader(new InputStreamReader(is)); //3.提取符合郵箱的數(shù)據(jù) String regex="\w+@\w+(\.\w+)+"; //進(jìn)行匹配 //將正則規(guī)則封裝成對(duì)象 Pattern p=Pattern.compile(regex); //將提取到的數(shù)據(jù)放到一個(gè)集合中 List<String> list=new ArrayList<String>(); String line=null; while((line=br.readLine())!=null){ //匹配器 Matcher m=p.matcher(line); while(m.find()){ //3.將符合規(guī)則的數(shù)據(jù)存儲(chǔ)到集合中 list.add(m.group()); } } return list; } }
注意:在執(zhí)行前需要先開(kāi)啟tomcat服務(wù)器
運(yùn)行結(jié)果:
總結(jié)
以上所述是小編給大家介紹的使用正則表達(dá)式實(shí)現(xiàn)網(wǎng)頁(yè)爬蟲(chóng)的思路詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)網(wǎng)站的支持!