惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
A
About on SuperTechFans
博客园 - Franky
Engineering at Meta
Engineering at Meta
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
B
Blog
Microsoft Security Blog
Microsoft Security Blog
L
LangChain Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
Martin Fowler
Martin Fowler
Y
Y Combinator Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 叶小钗
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
Last Week in AI
Last Week in AI
腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
爱范儿
爱范儿
V
V2EX
G
Google Developers Blog

博客园 - chensss2008

JavaScript 中的undefined and null 学习 html5 file upload and form data by ajax openresty + lua-resty-weedfs + weedfs + graphicsmagick动态生成缩略图(类似淘宝方案) ubuntu10.04 安装oracle server 版 笔记 windows xp + mysql5.5 + phpmyadmin insert 中文繁體 (原创)ubuntu 10.04+ruby1.9.2+rails3 安装记录 ruby簡單的代碼行統計工具 Ruby中如何复制对象 (deep clone)(转载) vi 常用命令使用說明 ruby1.9.2 +windowxp svn Server sent unexpected return value (403 Forbidden) in response to CHECKOUT ubuntu 14.04 安装svn server (subversionedge ) ubuntu 13.10 install wireshark Ubuntu 14.10下基于Nginx搭建mp4/flv流媒体服务器(可随意拖动)并支持RTMP/HLS协议(含转码工具) mysql distinct field1,field2,field3, .... from table jsoup 使用总结3--高级用法之 not jsoup 使用总结2--高级用法之 :gt(n) jsoup 使用总结1--添加header require './ex25' can't load such file
jsoup 使用总结4--高级用法之 script js 脚本
chensss2008 · 2015-07-22 · via 博客园 - chensss2008

jsoup 使用总结4--高级用法之 script js 脚本

大部分时候,我们使用jsoup解析网页的时候,都是直接找到某一类元素,或者按某种selector查询;具体使用方法可以参考jsoup官网文档
那么你有没有实际操作过,查找script js 脚本呢,因为很多时候页面的内容是根据js动态生成的,或者数据是动态变更;那么这个时候,我们只是获取html页面中script js脚本之间的内容。

部分html代码:

....

java代码:

Document doc = Jsoup.connect("www.example.com").timeout(0).get();
Elements links = doc.select("div.example_row").select("a");
for(Element link : links)
{
String linkHref = link.attr("href");
String linkText = link.text();
...
}
Element link = doc.select("a").first();
Element link_2 = doc.select("a").last();

上面的方式就可以帮我们查找到js 中的数据。

还有一种我在实际工作中遇到的情况, js 很复杂,并不像上面的那么一下子就可以catch到:
html代码:

那么针对这种情况jsoup如何破解呢,享受在jsoup的便捷中,思考,搜索,仍然误解;
发现这种问题jsoup还真解决不了。
那就换正则表达式试试。这里推荐一个在线正则工具 regexr
换了正则,然后不停的try,终于ok了:
java 代码:

Document doc = Jsoup.connect("www.example.com").timeout(0).get();
Elements scripts = doc.select("script");
for(Element script : scripts)
{
if(script.html().contains("var option_1 =")) //注意这里一定是html(), 而不是text()
{
String str = data.html().replace("\n", ""); //这里是为了解决 无法多行匹配的问题
String pattern = "var option_1 = \{(.*?)\};"; //()必须加,

Pattern r = Pattern.compile(pattern,Pattern.MULTILINE);// Pattern.MULTILINE 好像没有什么用,所以才使用上面的replace
Matcher m = r.matcher(str);
if(m.find())
{
String option_1 = m.group();
option_h24 = option_h24.replace("var option_1 = ", "");
JSONObject json = new JSONObject(option_1);
...

}
...
}

希望能解决你手边的问题。

另外推荐阅读jsoup的官网文档,我80%的问题都在官网找到了方法。