package cn.com.czj.front.utils.http; import java.io.*; import org.apache.commons.lang3.StringUtils; import org.htmlparser.Parser; import org.htmlparser.beans.StringBean; import org.htmlparser.util.ParserException; import org.htmlparser.visitors.HtmlPage; class GetPureWord { public static void main(String[] argv) throws IOException, InterruptedException, ParserException { Parser parser; String body = ""; String title = ""; String url = "http://www.linweikun.com/"; try { parser = new Parser(url); parser.setEncoding("UTF-8"); HtmlPage htmlpage = new HtmlPage(parser); parser.visitAllNodesWith(htmlpage); // 經過htmlparser 獲取body內容 body = htmlpage.getBody().asString(); // 經過htmlparser 獲取title內容 title = htmlpage.getTitle(); body = body.replaceAll("[ \\t\\n\\r\\f( |gt) ]+", " "); System.out.println(title); System.out.println(body); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } // System.out.println(StringUtils.replace(getText(url), "\n","")); // System.out.println(StringUtils.replacePattern(getText(url), // "\\s*|\t|\r|\n", "")); // System.out.println(StringUtils.replacePattern(getText(url), "\\s+", // " ")); System.out.println(StringUtils.replacePattern(StringUtils.replace(getText(url), "\n", ""), "\\s+", " ")); } /** * 根據提供的URL,獲取此URL對應網頁的純文本信息 * * @param url * 提供的URL連接 * @return RL對應網頁的純文本信息 * @throws ParserException */ public static String getText(String url) throws ParserException { StringBean sb = new StringBean(); // 設置不須要獲得頁面所包含的連接信息 sb.setLinks(true); // 設置將不間斷空格由正規空格所替代 // sb.setReplaceNonBreakingSpaces(true); // 設置將一序列空格由一個單一空格所代替 // sb.setCollapse(true); // 傳入要解析的URL sb.setURL(url); // 返回解析後的網頁純文本信息 return sb.getStrings(); } }