使用正則表達式實(shí)現網(wǎng)頁(yè)爬蟲(chóng)的思路解讀
優(yōu)采云 發(fā)布時(shí)間: 2020-05-06 08:04網(wǎng)頁(yè)爬蟲(chóng):就是一個(gè)程序用于在互聯(lián)網(wǎng)中獲取指定規則的數據。
思路:
1.為模擬網(wǎng)頁(yè)爬蟲(chóng),我們可以如今我們的tomcat服務(wù)器端布署一個(gè)1.html網(wǎng)頁(yè)。(部署的步驟:在tomcat目錄的webapps目錄的ROOTS目錄下新建一個(gè)1.html。使用notepad++進(jìn)行編輯網(wǎng)絡(luò )爬蟲(chóng) 正則表達式,編輯內容為:
?。?/p>
2.使用URL與網(wǎng)頁(yè)構建聯(lián)系
3.獲取輸入流,用于讀取網(wǎng)頁(yè)中的內容
4.建立正則規則,因為這兒我們是爬去網(wǎng)頁(yè)中的郵箱信息網(wǎng)絡(luò )爬蟲(chóng) 正則表達式,所以構建匹配 郵箱的正則表達式:String regex="\w+@\w+(\.\w+)+";
5.將提取到的數據放在集合中。
代碼:
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)中獲取指定規則的數據
*
*
*/
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ě)雙斜杠是用于轉義
URL url=new URL(path);
//2.獲取輸入流
InputStream is=url.openStream();
//加緩沖
BufferedReader br=new BufferedReader(new InputStreamReader(is));
//3.提取符合郵箱的數據
String regex="\w+@\w+(\.\w+)+";
//進(jìn)行匹配
//將正則規則封裝成對象
Pattern p=Pattern.compile(regex);
//將提取到的數據放到一個(gè)集合中
List<String> list=new ArrayList<String>();
String line=null;
while((line=br.readLine())!=null){
//匹配器
Matcher m=p.matcher(line);
while(m.find()){
//3.將符合規則的數據存儲到集合中
list.add(m.group());
}
}
return list;
}
}
注意:在執行前須要先開(kāi)啟tomcat服務(wù)器
運行結果:
總結
以上所述是小編給你們介紹的使用正則表達式實(shí)現網(wǎng)頁(yè)爬蟲(chóng)的思路解讀,希望對你們有所幫助,如果你們有任何疑惑請給我留言,小編會(huì )及時(shí)回復你們的。在此也特別謝謝你們對優(yōu)采云的支持!



