/** * 獲取html中body的內容 包含body標簽 * @param htmlStr html代碼 * @return */ public static String getBody(String htmlStr){ String pattern = "<body[^>]*>([\\s\\S]*)<\\/body>"; Pattern p_body = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); Matcher m_body = p_body.matcher(htmlStr); if (m_body.find()){ return m_body.group(); } return htmlStr; } /** * 取到html中body里面的內容 不包含body標簽 * @param htmlStr * @return */ public static String removeBody(String htmlStr){ /** * 獲取html代碼中body標簽里的內容 */ htmlStr=getBody(htmlStr); //body開頭標簽 String bodyEx_start = "<body[^>]*>"; //body結尾標簽 String bodyEx_end = "<\\/body>"; Pattern p_script = Pattern.compile(bodyEx_start, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 過濾script標簽 Pattern p_style = Pattern.compile(bodyEx_end, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 過濾style標簽 return htmlStr; }
如果要取得html代碼中body里面的內容 不包含body標簽
直接調用 removeBody