【问题标题】:How to parse html from javascript variables with Jsoup in Java?如何使用 Java 中的 Jsoup 从 javascript 变量中解析 html?
【发布时间】:2013-07-29 03:07:46
【问题描述】:

我正在使用 Jsoup 解析 html 文件并从元素中提取所有可见文本。问题是 javascript 变量中有一些 html 位显然被忽略了。解决这些问题的最佳解决方案是什么?

例子:

<!DOCTYPE html>
<html>
<head>
    <script>
        var html = "<span>some text</span>";
    </script>
</head>
<body>
    <p>text</p>
</body>
</html>

在这个例子中,Jsoup 只从p 标签中提取文本,这是它应该做的。如何从var html span 中提取文本?该解决方案必须应用于数千个不同的页面,所以我不能依赖于具有相同名称的 javascript 变量之类的东西。

【问题讨论】:

  • 至少你确定html的内容在双引号内,并且&lt;script&gt;标签内的双引号内没有其他内容吗?

标签: java javascript html jsoup


【解决方案1】:

您可以使用Jsoup将所有&lt;script&gt;-tags解析成DataNode-objects。

DataNode

一个数据节点,用于样式、脚本标签等内容,其中内容不应显示在 text() 中。

 Elements scriptTags = doc.getElementsByTag("script");

这将为您提供标签 &lt;script&gt; 的所有元素。

然后您可以使用getWholeData()-方法来提取节点。

// Get the data contents of this node.
String    getWholeData() 
 for (Element tag : scriptTags){                
        for (DataNode node : tag.dataNodes()) {
            System.out.println(node.getWholeData());
        }        
  }

Jsoup API - DataNode

【讨论】:

    【解决方案2】:

    我不太确定答案,但我在here之前看到过类似的情况。

    您可能可以根据该答案使用 Jsoup 和手动解析来获取文本。

    我只是根据您的具体情况修改那段代码:

    Document doc = ...
    Element script = doc.select("script").first(); // Get the script part
    
    
    Pattern p = Pattern.compile("(?is)html = \"(.+?)\""); // Regex for the value of the html
    Matcher m = p.matcher(script.html()); // you have to use html here and NOT text! Text will drop the 'html' part
    
    
    while( m.find() )
    {
        System.out.println(m.group()); // the whole html text
        System.out.println(m.group(1)); // value only
    }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多