[网络爬虫] Jsoup : HTML 解析工具

打印 上一主题 下一主题

主题 882|帖子 882|积分 2648

1 概述


简介



  • Jsoup是一款基于Java的HTML解析器,它提供了一种简单、机动且易于利用的API,用于从URL、文件或字符串中解析HTML文档。它可以帮助开辟人员从HTML文档中提取数据、操作DOM元素、处置惩罚表单提交等。

主要特点

   Jsoup的主要特点包罗:
  

  • 简单易用:Jsoup提供了一系列简单的API,使得解析HTML变得非常容易。开辟人员可以利用类似于jQuery的选择器语法来选择DOM元素,从而方便地提取所需的数据。
  • 强大的HTML处置惩罚本领:Jsoup支持HTML5尺度,并且能够处置惩罚不完整或损坏的HTML文档。它可以自动修复HTML中的错误,并且在解析过程中保留原始的HTML结构。
  • 安全可靠:Jsoup内置了防止XSS攻击的机制,可以自动过滤恶意的HTML标签和属性,包管解析过程的安全性。
  • 支持CSS选择器:Jsoup支持利用CSS选择器来选择DOM元素,这使得开辟人员可以更加机动地定位和操作HTML文档中的元素。
  • 与Java集成:Jsoup是基于Java开辟的,可以与Java程序无缝集成。开辟人员可以利用Java的各种特性和库来处置惩罚解析后的数据。

应用场景

   Jsoup 在大数据、云盘算领域的应用场景包罗但不限于:
  

  • 网页数据抓取: Jsoup可以帮助开辟人员从网页中提取所需的数据,比方爬取消息、商品信息等。通过解析HTML文档,可以快速精确地获取所需的数据。
  • 数据清洗与处置惩罚: 在云盘算中,大量的数据需要进行清洗和处置惩罚。Jsoup可以帮助开辟人员解析HTML文档,提取出需要的数据,并进行进一步的处置惩罚和分析。
  • 网页内容分析: Jsoup可以帮助开辟人员对网页内容进行分析,比方提取关键词、统计标签出现次数等。这对于搜刮引擎优化、网页分析等领域非常有用。

竞品

   爬虫解析HTML文档的工具有:
  

  • [java] Jsoup
   

  • GitHub - jhy/jsoup: jsoup: the Java HTML parser, built for HTML editing, cleaning, scraping, and XSS safety.
  • https://jsoup.org/
  • https://mvnrepository.com/artifact/org.jsoup/jsoup/1.12.2
  

  • [python] Beautiful Jsoup
   

  • Beautiful Soup: We called him Tortoise because he taught us.
  • GitHub - DeronW/beautifulsoup at v4.4.0
  • https://beautifulsoup.readthedocs.io/
     

  • https://beautifulsoup.readthedocs.io/zh-cn/v4.4.0/
    回到顶部(Back to Top)
2 利用指南



  • 本章节,基于 1.14.3 版本

依靠引入

  1. <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
  2. <dependency>     
  3.         <groupId>org.jsoup</groupId>     
  4.         <artifactId>jsoup</artifactId>
  5.     <!-- 1.12.2 / 1.14.3 / 1.17.2 -->       
  6.         <version>1.14.3</version>
  7. </dependency>
复制代码

焦点 API




org.jsoup.Jsoup

  1. package org.jsoup;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.URL;
  6. import javax.annotation.Nullable;
  7. import org.jsoup.helper.DataUtil;
  8. import org.jsoup.helper.HttpConnection;
  9. import org.jsoup.nodes.Document;
  10. import org.jsoup.parser.Parser;
  11. import org.jsoup.safety.Cleaner;
  12. import org.jsoup.safety.Safelist;
  13. import org.jsoup.safety.Whitelist;
  14. public class Jsoup {
  15.     private Jsoup() {
  16.     }
  17.     public static Document parse(String html, String baseUri) {
  18.         return Parser.parse(html, baseUri);
  19.     }
  20.     public static Document parse(String html, String baseUri, Parser parser) {
  21.         return parser.parseInput(html, baseUri);
  22.     }
  23.     public static Document parse(String html, Parser parser) {
  24.         return parser.parseInput(html, "");
  25.     }
  26.     public static Document parse(String html) {
  27.         return Parser.parse(html, "");
  28.     }
  29.     public static Connection connect(String url) {
  30.         return HttpConnection.connect(url);
  31.     }
  32.     public static Connection newSession() {
  33.         return new HttpConnection();
  34.     }
  35.     public static Document parse(File file, @Nullable String charsetName, String baseUri) throws IOException {
  36.         return DataUtil.load(file, charsetName, baseUri);
  37.     }
  38.     public static Document parse(File file, @Nullable String charsetName) throws IOException {
  39.         return DataUtil.load(file, charsetName, file.getAbsolutePath());
  40.     }
  41.     public static Document parse(File file, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {
  42.         return DataUtil.load(file, charsetName, baseUri, parser);
  43.     }
  44.     public static Document parse(InputStream in, @Nullable String charsetName, String baseUri) throws IOException {
  45.         return DataUtil.load(in, charsetName, baseUri);
  46.     }
  47.     public static Document parse(InputStream in, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {
  48.         return DataUtil.load(in, charsetName, baseUri, parser);
  49.     }
  50.     public static Document parseBodyFragment(String bodyHtml, String baseUri) {
  51.         return Parser.parseBodyFragment(bodyHtml, baseUri);
  52.     }
  53.     public static Document parseBodyFragment(String bodyHtml) {
  54.         return Parser.parseBodyFragment(bodyHtml, "");
  55.     }
  56.     public static Document parse(URL url, int timeoutMillis) throws IOException {
  57.         Connection con = HttpConnection.connect(url);
  58.         con.timeout(timeoutMillis);
  59.         return con.get();
  60.     }
  61.     public static String clean(String bodyHtml, String baseUri, Safelist safelist) {
  62.         Document dirty = parseBodyFragment(bodyHtml, baseUri);
  63.         Cleaner cleaner = new Cleaner(safelist);
  64.         Document clean = cleaner.clean(dirty);
  65.         return clean.body().html();
  66.     }
  67.     /** @deprecated */
  68.     @Deprecated
  69.     public static String clean(String bodyHtml, String baseUri, Whitelist safelist) {
  70.         return clean(bodyHtml, baseUri, (Safelist)safelist);
  71.     }
  72.     public static String clean(String bodyHtml, Safelist safelist) {
  73.         return clean(bodyHtml, "", safelist);
  74.     }
  75.     /** @deprecated */
  76.     @Deprecated
  77.     public static String clean(String bodyHtml, Whitelist safelist) {
  78.         return clean(bodyHtml, (Safelist)safelist);
  79.     }
  80.     public static String clean(String bodyHtml, String baseUri, Safelist safelist, Document.OutputSettings outputSettings) {
  81.         Document dirty = parseBodyFragment(bodyHtml, baseUri);
  82.         Cleaner cleaner = new Cleaner(safelist);
  83.         Document clean = cleaner.clean(dirty);
  84.         clean.outputSettings(outputSettings);
  85.         return clean.body().html();
  86.     }
  87.     /** @deprecated */
  88.     @Deprecated
  89.     public static String clean(String bodyHtml, String baseUri, Whitelist safelist, Document.OutputSettings outputSettings) {
  90.         return clean(bodyHtml, baseUri, (Safelist)safelist, outputSettings);
  91.     }
  92.     public static boolean isValid(String bodyHtml, Safelist safelist) {
  93.         return (new Cleaner(safelist)).isValidBodyHtml(bodyHtml);
  94.     }
  95.     /** @deprecated */
  96.     @Deprecated
  97.     public static boolean isValid(String bodyHtml, Whitelist safelist) {
  98.         return isValid(bodyHtml, (Safelist)safelist);
  99.     }
  100. }
复制代码

org.jsoup.nodes.Node

关键 API



  • Jsoup遍历DOM树的方法
   

  • 根据id查找元素: getElementById(String id)
  • 根据标签查找元素: getElementsByTag(String tag)
  • 根据class查找元素: getElementsByClass(String className)
  • 根据属性查找元素: getElementsByAttribute(String key)
  • 兄弟遍历方法: siblingElements(), firstElementSibling(), lastElementSibling(); nextElementSibling(), previousElementSibling()
  • 层级之间遍历: parent(), children(), child(int index)
  这些方法会返回Element大概Elements节点对象,这些对象可以利用下面的方法获取一些属性:


  • attr(String key): 获取某个属性值
  • attributes(): 获取节点的所有属性
  • id(): 获取节点的id
  • className(): 获取当前节点的class名称
  • classNames(): 获取当前节点的所有class名称
  • text(): 获取当前节点的textNode内容
  • html(): 获取当前节点的 inner HTML
  • outerHtml(): 获取当前节点的 outer HTML
  • data(): 获取当前节点的内容,用于script大概style标签等
  • tag(): 获取标签
  • tagName(): 获取当前节点的标签名称
   有了这些API,就像 JQuery 一样很便利的操作DOM。
  

  • Jsoup也支持修改DOM树结构:
   

  • text(String value): 设置内容
  • html(String value): 直接替换HTML结构
  • append(String html): 元素后面添加节点
  • prepend(String html): 元素前面添加节点
  • appendText(String text), prependText(String text)
  • appendElement(String tagName), prependElement(String tagName)
  源码

  1. package org.jsoup.nodes;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Collections;
  6. import java.util.Iterator;
  7. import java.util.LinkedList;
  8. import java.util.List;
  9. import javax.annotation.Nullable;
  10. import org.jsoup.SerializationException;
  11. import org.jsoup.helper.Validate;
  12. import org.jsoup.internal.StringUtil;
  13. import org.jsoup.select.NodeFilter;
  14. import org.jsoup.select.NodeTraversor;
  15. import org.jsoup.select.NodeVisitor;
  16. public abstract class Node implements Cloneable {
  17.     static final List<Node> EmptyNodes = Collections.emptyList();
  18.     static final String EmptyString = "";
  19.     @Nullable
  20.     Node parentNode;
  21.     int siblingIndex;
  22.     protected Node() {
  23.     }
  24.     public abstract String nodeName();
  25.     protected abstract boolean hasAttributes();
  26.     public boolean hasParent() {
  27.         return this.parentNode != null;
  28.     }
  29.     public String attr(String attributeKey) {
  30.                 ...
  31.         }
  32.        
  33.     public abstract Attributes attributes();
  34.        
  35.     public int attributesSize() {
  36.         return this.hasAttributes() ? this.attributes().size() : 0;
  37.     }
  38.     public Node attr(String attributeKey, String attributeValue) {
  39.         attributeKey = NodeUtils.parser(this).settings().normalizeAttribute(attributeKey);
  40.         this.attributes().putIgnoreCase(attributeKey, attributeValue);
  41.         return this;
  42.     }
  43.     public boolean hasAttr(String attributeKey) {
  44.         Validate.notNull(attributeKey);
  45.         if (!this.hasAttributes()) {
  46.             return false;
  47.         } else {
  48.             if (attributeKey.startsWith("abs:")) {
  49.                 String key = attributeKey.substring("abs:".length());
  50.                 if (this.attributes().hasKeyIgnoreCase(key) && !this.absUrl(key).isEmpty()) {
  51.                     return true;
  52.                 }
  53.             }
  54.             return this.attributes().hasKeyIgnoreCase(attributeKey);
  55.         }
  56.     }
  57.     public Node removeAttr(String attributeKey) {
  58.         Validate.notNull(attributeKey);
  59.         if (this.hasAttributes()) {
  60.             this.attributes().removeIgnoreCase(attributeKey);
  61.         }
  62.         return this;
  63.     }
  64.     public Node clearAttributes() {
  65.         if (this.hasAttributes()) {
  66.             Iterator<Attribute> it = this.attributes().iterator();
  67.             while(it.hasNext()) {
  68.                 it.next();
  69.                 it.remove();
  70.             }
  71.         }
  72.         return this;
  73.     }
  74.     public abstract String baseUri();
  75.     protected abstract void doSetBaseUri(String var1);
  76.     public void setBaseUri(String baseUri) {
  77.         Validate.notNull(baseUri);
  78.         this.doSetBaseUri(baseUri);
  79.     }
  80.     public String absUrl(String attributeKey) {
  81.         Validate.notEmpty(attributeKey);
  82.         return this.hasAttributes() && this.attributes().hasKeyIgnoreCase(attributeKey) ? StringUtil.resolve(this.baseUri(), this.attributes().getIgnoreCase(attributeKey)) : "";
  83.     }
  84.     protected abstract List<Node> ensureChildNodes();
  85.     public Node childNode(int index) {
  86.         return (Node)this.ensureChildNodes().get(index);
  87.     }
  88.     public List<Node> childNodes() {
  89.         if (this.childNodeSize() == 0) {
  90.             return EmptyNodes;
  91.         } else {
  92.             List<Node> children = this.ensureChildNodes();
  93.             List<Node> rewrap = new ArrayList(children.size());
  94.             rewrap.addAll(children);
  95.             return Collections.unmodifiableList(rewrap);
  96.         }
  97.     }
  98.     public List<Node> childNodesCopy() {
  99.         List<Node> nodes = this.ensureChildNodes();
  100.         ArrayList<Node> children = new ArrayList(nodes.size());
  101.         Iterator var3 = nodes.iterator();
  102.         while(var3.hasNext()) {
  103.             Node node = (Node)var3.next();
  104.             children.add(node.clone());
  105.         }
  106.         return children;
  107.     }
  108.     public abstract int childNodeSize();
  109.     protected Node[] childNodesAsArray() {
  110.         return (Node[])this.ensureChildNodes().toArray(new Node[0]);
  111.     }
  112.     public abstract Node empty();
  113.     @Nullable
  114.     public Node parent() {
  115.         return this.parentNode;
  116.     }
  117.     @Nullable
  118.     public final Node parentNode() {
  119.         return this.parentNode;
  120.     }
  121.     public Node root() {
  122.         Node node;
  123.         for(node = this; node.parentNode != null; node = node.parentNode) {
  124.         }
  125.         return node;
  126.     }
  127.     @Nullable
  128.     public Document ownerDocument() {
  129.         Node root = this.root();
  130.         return root instanceof Document ? (Document)root : null;
  131.     }
  132.     public void remove() {
  133.         Validate.notNull(this.parentNode);
  134.         this.parentNode.removeChild(this);
  135.     }
  136.     public Node before(String html) {
  137.         this.addSiblingHtml(this.siblingIndex, html);
  138.         return this;
  139.     }
  140.     public Node before(Node node) {
  141.         Validate.notNull(node);
  142.         Validate.notNull(this.parentNode);
  143.         this.parentNode.addChildren(this.siblingIndex, node);
  144.         return this;
  145.     }
  146.     public Node after(String html) {
  147.         this.addSiblingHtml(this.siblingIndex + 1, html);
  148.         return this;
  149.     }
  150.     public Node after(Node node) {
  151.         Validate.notNull(node);
  152.         Validate.notNull(this.parentNode);
  153.         this.parentNode.addChildren(this.siblingIndex + 1, node);
  154.         return this;
  155.     }
  156.     private void addSiblingHtml(int index, String html) {
  157.         Validate.notNull(html);
  158.         Validate.notNull(this.parentNode);
  159.         Element context = this.parent() instanceof Element ? (Element)this.parent() : null;
  160.         List<Node> nodes = NodeUtils.parser(this).parseFragmentInput(html, context, this.baseUri());
  161.         this.parentNode.addChildren(index, (Node[])nodes.toArray(new Node[0]));
  162.     }
  163.     public Node wrap(String html) {
  164.         Validate.notEmpty(html);
  165.         Element context = this.parentNode != null && this.parentNode instanceof Element ? (Element)this.parentNode : (this instanceof Element ? (Element)this : null);
  166.         List<Node> wrapChildren = NodeUtils.parser(this).parseFragmentInput(html, context, this.baseUri());
  167.         Node wrapNode = (Node)wrapChildren.get(0);
  168.         if (!(wrapNode instanceof Element)) {
  169.             return this;
  170.         } else {
  171.             Element wrap = (Element)wrapNode;
  172.             Element deepest = this.getDeepChild(wrap);
  173.             if (this.parentNode != null) {
  174.                 this.parentNode.replaceChild(this, wrap);
  175.             }
  176.             deepest.addChildren(new Node[]{this});
  177.             if (wrapChildren.size() > 0) {
  178.                 for(int i = 0; i < wrapChildren.size(); ++i) {
  179.                     Node remainder = (Node)wrapChildren.get(i);
  180.                     if (wrap != remainder) {
  181.                         if (remainder.parentNode != null) {
  182.                             remainder.parentNode.removeChild(remainder);
  183.                         }
  184.                         wrap.after(remainder);
  185.                     }
  186.                 }
  187.             }
  188.             return this;
  189.         }
  190.     }
  191.     @Nullable
  192.     public Node unwrap() {
  193.         Validate.notNull(this.parentNode);
  194.         List<Node> childNodes = this.ensureChildNodes();
  195.         Node firstChild = childNodes.size() > 0 ? (Node)childNodes.get(0) : null;
  196.         this.parentNode.addChildren(this.siblingIndex, this.childNodesAsArray());
  197.         this.remove();
  198.         return firstChild;
  199.     }
  200.     private Element getDeepChild(Element el) {
  201.         List<Element> children = el.children();
  202.         return children.size() > 0 ? this.getDeepChild((Element)children.get(0)) : el;
  203.     }
  204.     void nodelistChanged() {
  205.     }
  206.     public void replaceWith(Node in) {
  207.         Validate.notNull(in);
  208.         Validate.notNull(this.parentNode);
  209.         this.parentNode.replaceChild(this, in);
  210.     }
  211.     protected void setParentNode(Node parentNode) {
  212.         Validate.notNull(parentNode);
  213.         if (this.parentNode != null) {
  214.             this.parentNode.removeChild(this);
  215.         }
  216.         this.parentNode = parentNode;
  217.     }
  218.     protected void replaceChild(Node out, Node in) {
  219.         Validate.isTrue(out.parentNode == this);
  220.         Validate.notNull(in);
  221.         if (in.parentNode != null) {
  222.             in.parentNode.removeChild(in);
  223.         }
  224.         int index = out.siblingIndex;
  225.         this.ensureChildNodes().set(index, in);
  226.         in.parentNode = this;
  227.         in.setSiblingIndex(index);
  228.         out.parentNode = null;
  229.     }
  230.     protected void removeChild(Node out) {
  231.         Validate.isTrue(out.parentNode == this);
  232.         int index = out.siblingIndex;
  233.         this.ensureChildNodes().remove(index);
  234.         this.reindexChildren(index);
  235.         out.parentNode = null;
  236.     }
  237.     protected void addChildren(Node... children) {
  238.         List<Node> nodes = this.ensureChildNodes();
  239.         Node[] var3 = children;
  240.         int var4 = children.length;
  241.         for(int var5 = 0; var5 < var4; ++var5) {
  242.             Node child = var3[var5];
  243.             this.reparentChild(child);
  244.             nodes.add(child);
  245.             child.setSiblingIndex(nodes.size() - 1);
  246.         }
  247.     }
  248.     protected void addChildren(int index, Node... children) {
  249.                 ...
  250.         }
  251.     protected void reparentChild(Node child) {
  252.         child.setParentNode(this);
  253.     }
  254.     private void reindexChildren(int start) {
  255.         if (this.childNodeSize() != 0) {
  256.             List<Node> childNodes = this.ensureChildNodes();
  257.             for(int i = start; i < childNodes.size(); ++i) {
  258.                 ((Node)childNodes.get(i)).setSiblingIndex(i);
  259.             }
  260.         }
  261.     }
  262.     public List<Node> siblingNodes() {
  263.         if (this.parentNode == null) {
  264.             return Collections.emptyList();
  265.         } else {
  266.             List<Node> nodes = this.parentNode.ensureChildNodes();
  267.             List<Node> siblings = new ArrayList(nodes.size() - 1);
  268.             Iterator var3 = nodes.iterator();
  269.             while(var3.hasNext()) {
  270.                 Node node = (Node)var3.next();
  271.                 if (node != this) {
  272.                     siblings.add(node);
  273.                 }
  274.             }
  275.             return siblings;
  276.         }
  277.     }
  278.     @Nullable
  279.     public Node nextSibling() {
  280.         if (this.parentNode == null) {
  281.             return null;
  282.         } else {
  283.             List<Node> siblings = this.parentNode.ensureChildNodes();
  284.             int index = this.siblingIndex + 1;
  285.             return siblings.size() > index ? (Node)siblings.get(index) : null;
  286.         }
  287.     }
  288.     @Nullable
  289.     public Node previousSibling() {
  290.         if (this.parentNode == null) {
  291.             return null;
  292.         } else {
  293.             return this.siblingIndex > 0 ? (Node)this.parentNode.ensureChildNodes().get(this.siblingIndex - 1) : null;
  294.         }
  295.     }
  296.     public int siblingIndex() {
  297.         return this.siblingIndex;
  298.     }
  299.     protected void setSiblingIndex(int siblingIndex) {
  300.         this.siblingIndex = siblingIndex;
  301.     }
  302.     public Node traverse(NodeVisitor nodeVisitor) {
  303.         Validate.notNull(nodeVisitor);
  304.         NodeTraversor.traverse(nodeVisitor, this);
  305.         return this;
  306.     }
  307.     public Node filter(NodeFilter nodeFilter) {
  308.         Validate.notNull(nodeFilter);
  309.         NodeTraversor.filter(nodeFilter, this);
  310.         return this;
  311.     }
  312.     public String outerHtml() {
  313.         StringBuilder accum = StringUtil.borrowBuilder();
  314.         this.outerHtml(accum);
  315.         return StringUtil.releaseBuilder(accum);
  316.     }
  317.     protected void outerHtml(Appendable accum) {
  318.         NodeTraversor.traverse(new OuterHtmlVisitor(accum, NodeUtils.outputSettings(this)), this);
  319.     }
  320.     abstract void outerHtmlHead(Appendable var1, int var2, Document.OutputSettings var3) throws IOException;
  321.     abstract void outerHtmlTail(Appendable var1, int var2, Document.OutputSettings var3) throws IOException;
  322.     public <T extends Appendable> T html(T appendable) {
  323.         this.outerHtml(appendable);
  324.         return appendable;
  325.     }
  326.     public String toString() {
  327.         return this.outerHtml();
  328.     }
  329.     protected void indent(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
  330.         accum.append('\n').append(StringUtil.padding(depth * out.indentAmount()));
  331.     }
  332.     public boolean equals(@Nullable Object o) {
  333.         return this == o;
  334.     }
  335.     public int hashCode() {
  336.         return super.hashCode();
  337.     }
  338.     public boolean hasSameValue(@Nullable Object o) {
  339.         if (this == o) {
  340.             return true;
  341.         } else {
  342.             return o != null && this.getClass() == o.getClass() ? this.outerHtml().equals(((Node)o).outerHtml()) : false;
  343.         }
  344.     }
  345.     public Node clone() {
  346.                 ...
  347.         }
  348.         ...
复制代码

org.jsoup.nodes.Element extends Node


org.jsoup.nodes.Document extends Element


应用场景


CASE : 解析 HTML文档 => 获得 Document 对象

  1. import org.jsoup.Jsoup;
  2. import org.jsoup.nodes.Document;
  3. String html = "<html><head><title>First parse</title></head><body><p>Parsed HTML into a doc.</p></body></html>";
  4. Document doc = Jsoup.parse(html);
复制代码

CASE : 解析 HTML 片段 => 获得 Document 对象

  1. import org.jsoup.Jsoup;
  2. import org.jsoup.nodes.Document;
  3. String html = "<div><p>Lorem ipsum.</p>";
  4. Document doc = Jsoup.parseBodyFragment(html);
  5. Element body = doc.body();
复制代码

CASE : 解析 URL => 获得 Document 对象

  1. org.jsoup.Connection connection = Jsoup.connect("http://example.com/");
  2. Document doc = connection.get();//HTTP Method = GET
  3. String title = doc.title();
复制代码
  还可以携带cookie等参数:(和Python的爬虫类似)
  1. Document doc = Jsoup.connect("http://example.com")   
  2. .data("query", "Java")   
  3. .userAgent("Mozilla")   
  4. .cookie("auth", "token")   
  5. .timeout(3000)   
  6. .post(); //HTTP Method = POST
复制代码

CASE : 解析 HTML 当地文件 => 获得 Document 对象

  1. File input = new File("/tmp/input.html");
  2. Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
  3. /**
  4. * 提取文件里面的文本信息
  5. */
  6. public static String openFile(String szFileName) {
  7.     try {
  8.         BufferedReader bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(szFileName)), ENCODE));
  9.         String szContent = "";
  10.         String szTemp;
  11.         while ((szTemp = bis.readLine()) != null) {
  12.             szContent += szTemp + "\n";
  13.         }
  14.         bis.close();
  15.         return szContent;
  16.     } catch (Exception e) {
  17.         return "";
  18.     }
  19. }
复制代码

CASE : Element#hasText()/text()/ownText()/wholeText()



  • HTML 文档
  1. <html>
  2. <head><title>JSoup Parse Demo</title></head>
  3. <body>
  4.     <div id="demoDivId" style="min-height: 48px;"> hello<span>world<b>!</b></span> </div>
  5.     <p>Parsed HTML into a doc.</p>
  6. </body>
  7. </html>
复制代码


  • Demo Code
  1. final static String classpath = ClassLoader.getSystemResource("").getPath();//如: /E:/source_code/xxx/xxx-bigdata/xxx-common-demo/target/classes/
  2. final static String htmlFilePath = classpath + "sample-dataset/html/demo.html";
  3. String htmlContent = htmlReader.readHtml( htmlFilePath );
  4. Document document = Jsoup.parse(htmlContent);
  5. Element element = document.body().getElementById("demoDivId");
  6. log.info("cssSelector:{}", element.cssSelector());//cssSelector:#demoDivId
  7. log.info( "hasText:{}" , element.hasText() ); //hasText:true
  8. log.info( "text:{}" , element.text() );text:helloworld!
  9. log.info( "ownText:{}" , element.ownText() ); ownText:hello
  10. log.info( "wholeText:{}" , element.wholeText() ); wholeText: helloworld!
复制代码

CASE : Element#html()/outerHtml()



  • HTML 文档
   同上一案例
  

  • Demo Code
  1. ...
  2. Element element = document.body().getElementById("demoDivId");
  3. log.info( "html(innerHtml):{}" , element.html() );
  4. log.info( "outerHtml:\n{}" , element.outerHtml() );
复制代码


  • out
  1. html(innerHtml):hello<span>world<b>!</b></span>
  2. outerHtml:
  3. <div id="demoDivId" style="min-height: 48px;">
  4.   hello<span>world<b>!</b></span>
  5. </div>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

南七星之家

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表