html 在瀏覽器使用js可以很簡單的解析出來,獲取自己所需要的內(nèi)容或者值。
在Java代碼里我們可以使用:
javax.xml.parsers.DocumentBuilder
來解析html,來獲取需要的內(nèi)容或者值
來個示例:文章來源:http://www.zghlxwxcb.cn/news/detail-636028.html
public void test6() throws Exception {
//獲取DocumentBuilder
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//需要解析html
String html = "<span id='spanName_Q85fcFzaEY' attendee-id='5490'>tester1</span><div id='num_Q85fcFzaEY' class='attendee'>10</div>";
//這里需要一個完整的開始標簽和結(jié)束標簽,可以使用其他的,如果你的html是完整的,可以不加。
String html = "<a>"+html+"</a>";
Document document = documentBuilder.parse(new ByteArrayInputStream( html.getBytes()));
System.out.println(document.getElementsByTagName("span").item(0).getAttributes().getNamedItem("attendee-id").getNodeValue());
System.out.println(document.getElementsByTagName("div").item(0).getTextContent());
}
輸出結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-636028.html
5490
10
到了這里,關(guān)于java解析html的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!