安庆做网站的,天津seo优化,深圳网咯鸟网站建设公司怎么样,做海报的网站推荐Java XPath 使用#xff08;2023/08/29#xff09; 文章目录 Java XPath 使用#xff08;2023/08/29#xff09;1. 前言2. 技术选型3. 技术实现 1. 前言
众所周知#xff0c;Java 语言适合应用于 Web 开发领域#xff0c;不擅长用来编写爬虫。但在 Web 开发过程中有时又…Java XPath 使用2023/08/29 文章目录 Java XPath 使用2023/08/291. 前言2. 技术选型3. 技术实现 1. 前言
众所周知Java 语言适合应用于 Web 开发领域不擅长用来编写爬虫。但在 Web 开发过程中有时又存在爬取数据的需求此时采用其它语言编写独立爬虫模块的话存在维护不方便的问题所以此处笔者选择了使用 Java XPath 实现简单的爬虫功能如果爬虫需求较多且复杂还是推荐采用其它语言实现独立的爬虫模块。
2. 技术选型
JsoupXpath 优点使用简单缺点对 XPath 语法的支持有限 xsoup 优点使用简单缺点对 XPath 语法的支持有限 HtmlCleaner 优点使用简单缺点对 XPath 语法的支持有限 Java XPath 优点对 XPath 语法支持全面缺点对 xml 格式要求严格几乎没有 Html 可以通过解析 HtmlCleaner Java XPath 优点对 XPath 语法支持全面缺点使用相对复杂
3. 技术实现
以 http://www.jnswj.net/jsp/sw/jnsw-skhdsq.jsp 网站和 //*[idMainTable]/tbody/tr[position()5 and position()22]/td[position()1 or (position()9 and position()13)] XPath 表达式为例笔者测试了上述 5 种技术方案其中只有第 5 种方案通过了测试其它几种均出现了报错故此处仅介绍第 5 种方案的实现。 Maven 引入依赖 !-- 获取 HTML 页面内容 --
!-- https://mvnrepository.com/artifact/cn.hutool/hutool-http --
dependencygroupIdcn.hutool/groupIdartifactIdhutool-http/artifactIdversion5.8.21/version
/dependency!-- 解析 HTML --
!-- https://mvnrepository.com/artifact/net.sourceforge.htmlcleaner/htmlcleaner --
dependencygroupIdnet.sourceforge.htmlcleaner/groupIdartifactIdhtmlcleaner/artifactIdversion2.29/version
/dependency获取页面内容并解析获取结果 import cn.hutool.http.HttpUtil;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;/*** 测试 HtmlCleaner Java XPath.** author a hrefmailto:xiaoQQya126.comxiaoQQya/a* since 2023/08/29*/
private void test throws ParserConfigurationException, XPathExpressionException {// 获取 HTML 页面内容String url http://www.jnswj.net/jsp/sw/jnsw-skhdsq.jsp;String html HttpUtil.get(url);// 解析 HTML 页面内容HtmlCleaner hc new HtmlCleaner();TagNode tn hc.clean(html);Document document new DomSerializer(new CleanerProperties()).createDOM(tn);// 匹配获取需要的数据XPath xPath XPathFactory.newInstance().newXPath();String exp //*[id\MainTable\]/tbody/tr[position()5 and position()22]/td[position()1 or (position()9 and position()13)];NodeList nodes (NodeList) xPath.evaluate(exp, document, XPathConstants.NODESET);for (int length nodes.getLength(), i 0; i length; i) {Node item nodes.item(i);System.out.println(item.getTextContent());}
}参考文章
Java - XPath解析爬取内容 - Jinkora - 博客园 (cnblogs.com);Intro to XPath with Java | Baeldung;zhegexiaohuozi/JsoupXpath: 纯Java实现的支持W3C Xpath 1.0标准语法的HTML解析器。A html parser with xpath base on Jsoup and Antlr4. Maybe it is the best in java.Just try it. (github.com);code4craft/xsoup: When jsoup meets XPath. (github.com);