【问题标题】:JSoup get text and inline images in orderJSoup 按顺序获取文本和内联图像
【发布时间】:2018-07-25 23:20:41
【问题描述】:

我有一些看起来像这样的 HTML:

<tr>
  <td>
    Some text that is interrupted by an image here:
    <a href="/item" title="item"><img alt="imageName.png" src="linkhere" width="18" height="18"></a>
    and then continues here.
  </td>
</tr>

基本上我只需要一种方法来遍历此处的节点,然后使用 JSoup 将文本或图像 alt 添加到字符串中,从而保持节点的顺序。

最后应该是这样的:

此处被图片打断的一些文字:“imageName.png”,然后在此处继续

到目前为止,我可以通过以下方式单独获取图像或文本:

element.text();
//or
element.select("img").attr("alt")

但我无法将它们都放入有序列表中。

有什么想法吗?

【问题讨论】:

    标签: java html jsoup


    【解决方案1】:

    以下代码应为您提供您正在寻找的输出字符串。它基本上循环遍历文档中的所有节点,并确定它们是文本节点还是元素。如果它们是文本节点,它会将它们添加到输出字符串中。如果它们是元素,它将检查图像子元素并将替代文本添加到字符串中。

    String test = "";
    
    Element body = doc.getElementsByTag("body").first();
    List<Node> childNodes = body.childNodes();
    
    for(Node node : childNodes){
    
        if(node instanceof TextNode){
            // These are text nodes, lets see if they are empty or not and add them to the string.
            String nodeString = node.toString();
            if(nodeString != null && !nodeString.trim().isEmpty()){
                test += nodeString;
            }
        } else if (node instanceof Element) {
            // Here is an element, let's see if there is an image.
            Element element = (Element)node;
            Element image = element.children().select("img").first();
    
            if(image != null)
            {
                test += image.attr("alt");
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 2020-08-04
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      相关资源
      最近更新 更多