通過xpath擷取html中的特定標籤

來源:互聯網
上載者:User
package nekohtml;import java.io.IOException;import javax.xml.transform.TransformerException;import org.apache.xpath.XPathAPI;import org.cyberneko.html.parsers.DOMParser;import org.w3c.dom.Document;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class NekoHtmlAndXPath {// 通過url,將相應的html解析為DOM文檔public static Document getDocument(String url) {DOMParser parser = new DOMParser();try {parser.parse(url);} catch (SAXException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}Document doc = parser.getDocument();return doc;}// 通過XPath定位具體的節點public static NodeList getExactNode(Document doc, String xp) {NodeList list = null;try {list = XPathAPI.selectNodeList(doc, xp);} catch (TransformerException e) {e.printStackTrace();}return list;}public static void main(String[] args) {String baidu = "http://www.baidu.com/";String bPath = "//HTML//BODY//DIV[2]//P//MAP//AREA";String yyt = "http://www.yinyuetai.com/mv/all?page=1";String yPath = "/HTML/BODY/DIV[6]/DIV/DIV[2]/DIV[2]/DIV[3]/UL/LI/DIV[2]/H3/A";// 將指定的頁面解析為DOM文檔Document doc = getDocument(yyt);// 根據xpath獲得指定的節點NodeList list = getExactNode(doc, yPath);System.out.println("合格結點個數為:" + list.getLength());for (int i = 0; i < list.getLength(); i++) {System.out.println("擷取的節點屬性為:"+ list.item(i).getAttributes().getNamedItem("title"));}}}

 用到的jar包:xalan.jar;xercesImpl.jar;nekohtml.jar。

擷取標籤的XPath用到了firebug,有的時候需要做一些轉換,因為firebug把html轉換成了標準的DOM,所以會有極個別的xpath有點小問題。比如說可能會加上tbody標籤,稍作改動即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.