有这样一段HTML:
<div><table><td id='1234 foo 5678'>Hello</td>
希望通过这个XPath提取出Hello:
//div//td[contains(@id, 'foo')]/text()
先导入maven依赖:
1<!-- https://mvnrepository.com/artifact/net.sourceforge.htmlcleaner/htmlcleaner --> 2<dependency> 3 <groupId>net.sourceforge.htmlcleaner</groupId> 4 <artifactId>htmlcleaner</artifactId> 5 <version>2.21</version> 6</dependency>
main函数:
1package com.my.demo; 2 3import javax.xml.xpath.XPath; 4import javax.xml.xpath.XPathConstants; 5import javax.xml.xpath.XPathFactory; 6 7import org.htmlcleaner.CleanerProperties; 8import org.htmlcleaner.DomSerializer; 9import org.htmlcleaner.HtmlCleaner; 10import org.htmlcleaner.TagNode; 11import org.w3c.dom.Document; 12 13public class HtmlXpathJava { 14 public static void main(String[] args) { 15 String sampleHtml = "<div><table><td id='1234 foo 5678'>Hello</td>"; 16 String sampleXpath = "//div//td[contains(@id, 'foo')]/text()"; 17 System.out.println(getValueByXpath(sampleXpath, sampleHtml)); 18 } 19 20 /** 21 * Extract value by xPath from HTML. 22 */ 23 private static String getValueByXpath(String xPath, String html) { 24 TagNode tagNode = new HtmlCleaner().clean(html); 25 String value = null; 26 try { 27 Document doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode); 28 XPath xpath = XPathFactory.newInstance().newXPath(); 29 value = (String) xpath.evaluate(xPath, doc, XPathConstants.STRING); 30 } catch (Exception e) { 31 System.out.println("Extract value error. " + e.getMessage()); 32 e.printStackTrace(); 33 } 34 return value; 35 } 36}
输出:
Hello
参考:
https://stackoverflow.com/questions/9022140/using-xpath-contains-against-html-in-java