導語:Java如何正則表達式分析讀取網頁內容?下面是小編給大家提供的代碼實現,大家可以參考閱讀,更多詳情請關注應屆畢業生考試網。
Java用正則表達式分析讀取網頁內容
package p;
import eredReader;
import ception;
import tStreamReader;
import ormedURLException;
import ;
import yList;
import Map;
import ;
import her;
import ern;
/** *//**
*
* @抓取雅虎知識堂的文章標題及內容(測試) 手動輸入網址抓取,可進一步自動抓取整個知識堂的'全部內容
*
*/
public class WebContent ...{
/** *//**
* 讀取一個網頁全部內容
*/
public String getOneHtml(String htmlurl) throws IOException...{
URL url;
String temp;
StringBuffer sb = new StringBuffer();
try ...{
url = new URL(htmlurl);
BufferedReader in = new BufferedReader(new InputStreamReader(url
Stream(), "utf-8"));// 讀取網頁全部內容
while ((temp = Line()) != null) ...{
nd(temp);
}
e();
}catch(MalformedURLException me)...{
tln("你輸入的URL格式有問題!請仔細輸入");
essage();
throw me;
}catch (IOException e) ...{
tStackTrace();
throw e;
}
return ring();
}
/** *//**
*
* @param s
* @return 獲得網頁標題
*/
public String getTitle(String s) ...{
String regex;
String title = "";
List<String> list = new ArrayList<String>();
regex = "<title>.*?</title>";
Pattern pa = ile(regex, N_EQ);
Matcher ma = her(s);
while (()) ...{
(p());
}
for (int i = 0; i < (); i++) ...{
title = title + (i);
}
return outTag(title);
}
/** *//**
*
* @param s
* @return 獲得鏈接
*/
public List<String> getLink(String s) ...{
String regex;
List<String> list = new ArrayList<String>();
regex = "<a[^>]*href=("([^"]*)"|'([^']*)'|([^s>]*))[^>]*>(.*?)</a>";
Pattern pa = ile(regex, LL);
Matcher ma = her(s);
while (()) ...{
(p());
}
return list;
}
/** *//**
*
* @param s
* @return 獲得腳本代碼
*/
public List<String> getScript(String s) ...{
String regex;
List<String> list = new ArrayList<String>();
regex = "<script.*?</script>";
Pattern pa = ile(regex, LL);
Matcher ma = her(s);
while (()) ...{
(p());
}
return list;
}
/** *//**
*
* @param s
* @return 獲得CSS
*/
public List<String> getCSS(String s) ...{
String regex;
List<String> list = new ArrayList<String>();
regex = "<style.*?</style>";
Pattern pa = ile(regex, LL);
Matcher ma = her(s);
while (()) ...{
(p());
}
return list;
}
/** *//**
*
* @param s
* @return 去掉標記
*/
public String outTag(String s) ...{
return aceAll("<.*?>", "");
}