java脚本标记,Java - 使用Jsoup在脚本标记内获取文本

I am using the Jsoup library to read a URL. This url has text within a few tags. Is it possible for me to obtain the text within each 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:

(function() {

...

})();

解决方案

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("-------------------");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值