java 使用正則表達式從網頁上提取網站標題


如何從網頁上抓取有價值的東西?看懂了下面的程序(非常簡單),想從網頁上抓取什么信息(標題、內容、Email、價格等)就能抓取什么信息。

package catchhtml;
import java.io.BufferedReader;
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 GetHtmlTitle {
    
    public GetHtmlTitle(String htmlUrl){
        System.out.println("/n------------開始讀取網頁(" + htmlUrl + ")-----------");
        String htmlSource = "";
        htmlSource = getHtmlSource(htmlUrl);//獲取htmlUrl網址網頁的源碼
        System.out.println("------------讀取網頁(" + htmlUrl + ")結束-----------/n");
        System.out.println("------------分析(" + htmlUrl + ")結果如下-----------/n");
        String title = getTitle(htmlSource);
        System.out.println("網站標題: " + title);
    }
    
    /**
     * 根據網址返回網頁的源碼
     * @param htmlUrl
     * @return
     */
    public String getHtmlSource(String htmlUrl){
        URL url;    
        StringBuffer sb = new StringBuffer();
        try{
            url = new URL(htmlUrl);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));//讀取網頁全部內容
            String temp;
            while ((temp = in.readLine()) != null)
            {            
                sb.append(temp);
            }
            in.close();
        }catch (MalformedURLException e) {
            System.out.println("你輸入的URL格式有問題!請仔細輸入");
        }catch (IOException e) {
            e.printStackTrace();
        }    
        return sb.toString();
    }
    
    /**
     * 從html源碼(字符串)中去掉標題
     * @param htmlSource
     * @return
     */
    public String getTitle(String htmlSource){
        List<String> list = new ArrayList<String>();
        String title = "";
        
        //Pattern pa = Pattern.compile("<title>.*?</title>", Pattern.CANON_EQ);也可以
        Pattern pa = Pattern.compile("<title>.*?</title>");//源碼中標題正則表達式
        Matcher ma = pa.matcher(htmlSource);
        while (ma.find())//尋找符合el的字串
        {
            list.add(ma.group());//將符合el的字串加入到list中
        }
        for (int i = 0; i < list.size(); i++)
        {
            title = title + list.get(i);
        }
        return outTag(title);
    }
    
    /**
     * 去掉html源碼中的標簽
     * @param s
     * @return
     */
    public String outTag(String s)
    {
        return s.replaceAll("<.*?>", "");
    }
    
    public static void main(String[] args) {
        String htmlUrl = "http://www.157buy.com";
        new GetHtmlTitle(htmlUrl);

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM