Java - 使用Jsoup在脚本标记内获取文本 [英] Java - Obtain text within script tag using Jsoup
问题描述
我正在使用Jsoup库来读取URL。此网址包含少量< script>
标记内的文字。我是否可以在每个< script>
标记内获取文字?请注意,我并不是要求解析Javascript文件,因为我已经知道JSoup不允许这样做。 URL的实际源代码在脚本标记中有文本,我需要它。
I am using the Jsoup library to read a URL. This url has text within a few <script>
tags. Is it possible for me to obtain the text within each <script>
tag? Please note that I am not asking to parse a Javascript file as I am already aware JSoup does not allow that. The actual source code of the URL has text within a script tag, I need that.
doc = Jsoup.connect("http://www.example.com").timeout(10000).get();
Element div = doc.select("script").first();
for (Element element : div.children()) {
System.out.println(element.toString());
}
这是源代码中的一个脚本标记:
This is what one of the script tags look like from the source code:
<script type="text/javascript">
(function() {
...
})();
</script>
推荐答案
是的。您可以使用 Element#getElementsByTag()来获取所有脚本
标记。每个脚本标记都将由 DataNode 表示。
Yes. You can use Element#getElementsByTag() to get all the script
tag . Each script tags will be represented by the DataNode.
Document doc =Jsoup.connect("http://stackoverflow.com/questions/16780517/java-obtain-text-within-script-tag-using-jsoup").timeout(10000).get();
Elements scriptElements = doc.getElementsByTag("script");
for (Element element :scriptElements ){
for (DataNode node : element.dataNodes()) {
System.out.println(node.getWholeData());
}
System.out.println("-------------------");
}
这篇关于Java - 使用Jsoup在脚本标记内获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!