網頁爬蟲:就是一個程序用于在互聯網中獲取指定規則的數據。
思路:
1.為模擬網頁爬蟲,我們可以現在我們的tomcat服務器端部署一個1.html網頁。(部署的步驟:在tomcat目錄的webapps目錄的ROOTS目錄下新建一個1.html。使用notepad++進行編輯,編輯內容為:
)
2.使用URL與網頁建立聯系
3.獲取輸入流,用于讀取網頁中的內容
4.建立正則規則,因為這里我們是爬去網頁中的郵箱信息,所以建立匹配 郵箱的正則表達式: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;/* * 網頁爬蟲:就是一個程序用于在互聯網中獲取指定規則的數據 * * */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.與網頁建立聯系。使用URL String path="http://localhost:8080//1.html";//后面寫雙斜杠是用于轉義 URL url=new URL(path); //2.獲取輸入流 InputStream is=url.openStream(); //加緩沖 BufferedReader br=new BufferedReader(new InputStreamReader(is)); //3.提取符合郵箱的數據 String regex="http://w+@//w+(//.//w+)+"; //進行匹配 //將正則規則封裝成對象 Pattern p=Pattern.compile(regex); //將提取到的數據放到一個集合中 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; }}
注意:在執行前需要先開啟tomcat服務器
運行結果:
總結
以上所述是小編給大家介紹的使用正則表達式實現網頁爬蟲的思路詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答
圖片精選