htmlcleaner使用方法及xpath语法初探

前端技术 2023/09/03 Java

在编程的时候或者写网络爬虫的时候,经常需要对html进行解析,抽取其中有用的数据。一款好的工具是特别有用的,能提供很多的帮助,网上有很多这样的工具,比如:htmlcleaner、htmlparser

经使用比较:感觉 htmlcleaner 比 htmlparser 好用,尤其是htmlcleaner 的 xpath特好用。

下面针对htmlcleaner进行举例说明,需求为:取出title,name=”my_href” 的链接,div的class=”d_1″下的所有li内容。

一、HtmlCleaner使用:

1、HtmlCleaner

HtmlCleaner是一个开源的Java语言的Html文档解析器。HtmlCleaner能够重新整理HTML文档的每个元素并生成结构良好(Well-Formed)的 HTML 文档。默认它遵循的规则是类似于大部份web浏览器为创文档对象模型所使用的规则。然而,用户可以提供自定义tag和规则组来进行过滤和匹配。

主页地址:http://htmlcleaner.sourceforge.net/

下载地址:http://www.phpstudy.net/softs/364983.html


2、基本示例,在wikipedia中抓取机场信息

html-clean-demo.html

html-clean-demo.html
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd \">
<html xmlns = \"http://www.w3.org/1999/xhtml \" xml:lang = \"zh-CN\" dir = \"ltr\">
<head>
	<meta http-equiv = \"Content-Type\" content = \"text/html; charset=GBK\" /> 
	<meta http-equiv = \"Content-Language\" content = \"zh-CN\" /> 
	<title>html clean demo </title>
</head>
<body>
<div class = \"d_1\">
	<ul>
		<li>bar </li>
		<li>foo </li>
		<li>gzz </li>
	</ul>
</div>
<div>
	<ul>
		<li><a name = \"my_href\" href = \"1.html\">text-1 </a></li>
		<li><a name = \"my_href\" href = \"2.html\">text-2 </a></li>
		<li><a name = \"my_href\" href = \"3.html\">text-3 </a></li>
		<li><a name = \"my_href\" href = \"4.html\">text-4 </a></li>
	</ul>
</div>
</body>
</html>

HtmlCleanerDemo.java

package com.chenlb;
import java.io.File;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
/**
 * htmlcleaner 使用示例.
 *
 */
public class HtmlCleanerDemo {
	public static void main(String[] args) throws Exception {
		HtmlCleaner cleaner = new HtmlCleaner();
		TagNode node = cleaner.clean(new File(\"html/html-clean-demo.html\"), \"GBK\");
		//按tag取.
		Object[] ns = node.getElementsByName(\"title\", true);	//标题
		if(ns.length > 0) {
			System.out.println(\"title=\"+((TagNode)ns[0]).getText());
		}
		System.out.println(\"ul/li:\");
		//按xpath取
		ns = node.evaluateXPath(\"//div[@class=\'d_1\']//li\");
		for(Object on : ns) {
			TagNode n = (TagNode) on;
			System.out.println(\"\\ttext=\"+n.getText());
		}
		System.out.println(\"a:\");
		//按属性值取
		ns = node.getElementsByAttValue(\"name\", \"my_href\", true, true);
		for(Object on : ns) {
			TagNode n = (TagNode) on;
			System.out.println(\"\\thref=\"+n.getAttributeByName(\"href\")+\", text=\"+n.getText());
		}
	}
}

cleaner.clean()中的参数,可以是文件,可以是url,可以是字符串内容。比较常用的应该是evaluateXPath、 getElementsByAttValue、getElementsByName方法了。另外说明下,htmlcleaner 对不规范的html兼容性比较好。

在wikipedia中抓取机场信息

import java.io.UnsupportedEncodingException;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import com.moore.index.BabyStory;
import com.moore.util.HttpClientUtil;
/**
 * 用途:TODO
 * 
 * @author bbdtek
 */
public class ParserAirport {
	private static Logger log = LoggerFactory.getLogger(ParserAirport.class);
	/**
	 * @param args
	 * @throws UnsupportedEncodingException
	 * @throws XPatherException
	 */
	public static void main(String[] args) throws UnsupportedEncodingException,
			XPatherException {
		String url = \"http://zh.wikipedia.org/wiki/%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD%E6%9C%BA%E5%9C%BA%E5%88%97%E8%A1%A8\";
		String contents = HttpClientUtil.getUtil().getCon(url);
		HtmlCleaner hc = new HtmlCleaner();
		TagNode tn = hc.clean(contents);
		String xpath = \"//div[@class=\'mw-content-ltr\']//table[@class=\'wikitable + sortable\']//tbody//tr[@align=\'right\']\";
		Object[] objarr = null;
		objarr = tn.evaluateXPath(xpath);
		if (objarr != null && objarr.length > 0) {
			for (Object obj : objarr) {
				TagNode tntr = (TagNode) obj;
				String xptr = \"//td[@align=\'left\']//a\";
				Object[] objarrtr = null;
				objarrtr = tntr.evaluateXPath(xptr);
				if (objarrtr != null && objarrtr.length > 0) {
					for (Object obja : objarrtr) {
						TagNode tna = (TagNode) obja;
						String str = tna.getText().toString();
						log.info(str);
					}
				}
			}
		}
	}
}

二、XPath初探

1、XPath简介:

XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。

2、XPath节点选取


XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。

下面列出了最有用的路径表达式:

表达式 描述
nodename 选取此节点的所有子节点。
/ 从根节点选取。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
.. 选取当前节点的父节点。
@ 选取属性。

一些常用表达式

路径表达式 结果
/bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()<3] 选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang] 选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang=\'eng\'] 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00] 选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title 选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。

本文地址:https://www.stayed.cn/item/8897

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。