如何使用Java中的Jsoup从javascript变量解析html?
我使用Jsoup解析html文件并从元素中提取所有可见文本。问题是javascript变量中有一些html位显然被忽略了。什么是最好的解决方案,以获得这些比特 例如:如何使用Java中的Jsoup从javascript变量解析html?,java,javascript,html,jsoup,Java,Javascript,Html,Jsoup,我使用Jsoup解析html文件并从元素中提取所有可见文本。问题是javascript变量中有一些html位显然被忽略了。什么是最好的解决方案,以获得这些比特 例如: <!DOCTYPE html> <html> <head> <script> var html = "<span>some text</span>"; </script> </head> <body
<!DOCTYPE html>
<html>
<head>
<script>
var html = "<span>some text</span>";
</script>
</head>
<body>
<p>text</p>
</body>
</html>
var html=“一些文本”;
正文
在本例中,Jsoup只从
p
标记中提取文本,这是它应该做的。如何从var html
span中提取文本?该解决方案必须应用于数千个不同的页面,因此我不能依赖于具有相同名称的javascript变量。您可以使用Jsoup将所有
-标记解析为DataNode
-对象
DataNode
数据节点,用于样式、脚本标记等的内容,其中内容不应显示在text()中
这将为您提供标签
的所有元素
然后可以使用getWholeData()
-方法提取节点
我不太确定答案,但我以前也看到过类似的情况 您可能可以使用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
}
希望对您有所帮助。至少您确定
html
内容在双引号中,并且
标记中没有其他内容在双引号中吗?
// Get the data contents of this node.
String getWholeData()
for (Element tag : scriptTags){
for (DataNode node : tag.dataNodes()) {
System.out.println(node.getWholeData());
}
}
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
}