使用jsoup解析JavaScript

时间:2013-02-15 22:58:04

标签: java javascript html jsoup

HTML页面中,我想选择javascript变量的值。以下是HTML页面的摘要。

<input id="hidval" value="" type="hidden"> 
<form method="post" style="padding: 0px;margin: 0px;" name="profile" autocomplete="off">
<input name="pqRjnA" id="pqRjnA" value="" type="hidden">
<script type="text/javascript">
    key="pqRjnA";
</script>

我的目标是使用key从此页面读取变量jsoup的值。 jsoup可以吗?如果是,那怎么样?

1 个答案:

答案 0 :(得分:30)

由于jsoup不是一个javascript库,你有两种解决方法:

甲。使用javascript库

  • <强>临

    • 完整的Javascript支持
  • <强>缺点:

    • 其他libraray / dependencies

B中。使用Jsoup +手动解析

  • <强>临

    • 无需额外的库
    • 足够简单的任务
  • <强>缺点:

    • 不像javascript库那样灵活

以下是如何使用jsoup和一些“manual”代码获取key的示例:

Document doc = ...
Element script = doc.select("script").first(); // Get the script part


Pattern p = Pattern.compile("(?is)key=\"(.+?)\""); // Regex for the value of the key
Matcher m = p.matcher(script.html()); // you have to use html here and NOT text! Text will drop the 'key' part


while( m.find() )
{
    System.out.println(m.group()); // the whole key ('key = value')
    System.out.println(m.group(1)); // value only
}

输出(使用您的html部分):

key="pqRjnA"
pqRjnA