如何在Java中使用Jsoup从javascript变量解析html

How to parse html from javascript variables with Jsoup in Java?

本文关键字:javascript 变量 html Jsoup Java      更新时间:2023-09-26

我使用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变量。

您可以使用Jsoup将所有<script>-标记解析为DataNode-对象。

DataNode

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

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

这将为您提供标记<script>的所有元素。

然后可以使用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-数据节点

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

您可能可以使用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
}

希望对你有所帮助。