使用jsoup解析JavaScript

Rav*_*shi 12 html javascript java 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>
Run Code Online (Sandbox Code Playgroud)

我的目标是key使用此页面读取变量的值jsoup.有可能jsoup吗?如果是的话怎么样?

oll*_*llo 30

由于jsoup不是一个javascript库,你有两种方法可以解决这个问题:

A.使用JavaScript库

  • 优点:

    • 完整的Javascript支持
  • 缺点:

    • 额外的libraray/dependencies

B.使用Jsoup +手动解析

  • 优点:

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

    • 不如javascript库灵活

这是一个如何key使用jsoup和一些"手动"代码的示例:

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
}
Run Code Online (Sandbox Code Playgroud)

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

key="pqRjnA"
pqRjnA
Run Code Online (Sandbox Code Playgroud)