android - 如何在android编程中使用jsoup从html获取此脚本

标签 android html json jsoup

我想从 html 页面的 scriptjsoup 获取字符串值。但也存在一些问题:

  1. 该页面中有六个脚本。我想用 jsoup 选择 forth of all(我的意思是数字 4)。我不知道我该怎么做。
  2. 该脚本中有一个键,我想捕获该键的值

在这里你可以看到想要的脚本:

<script type="text/javascript">window._sharedData={

  "entry_data": {
    "PostPage": [
      {
        "media": {

          "key": "This is the key and i wanna catch it!!!",

        },      
      }
    ]
  },

};</script>

我尝试了很多方法,但都没有成功。

我期待着得到答案,所以请不要让我失望!

最佳答案

JSoup 只会帮助您获取脚本标签的内容作为字符串。它解析 HTML,而不是 JavaScript 脚本内容。由于在您的情况下,脚本的内容是 JSON 表示法中的一个简单对象,您可以在获取脚本字符串并剥离变量赋值后使用 JSON 解析器。在下面的代码中,我使用 JSON simple解析器。

String html = "<script></script><script></script><script></script>"
    +"<script type=\"text/javascript\">window._sharedData={"
    +"  \"entry_data\": {"
    +"    \"PostPage\": ["
    +"      {"
    +"        \"media\": {"
    +"          \"key\": \"This is the key and i wanna catch it!!!\","
    +"        },"
    +"      }"
    +"    ]"
    +"  },"
    +"};</script><script></script>";
Document doc = Jsoup.parse(html);
//get the 4th script
Element scriptEl = doc.select("script").get(3);
String scriptContentStr = scriptEl.html();
//clean to get json
String jsonStr = scriptContentStr
     .replaceFirst("^.*=\\{", "{") //clean beginning
     .replaceFirst("\\;$", ""); //clean end
JSONObject jo = (JSONObject) JSONValue.parse(jsonStr);
JSONArray postPageJA = ((JSONArray)((JSONObject)jo.get("entry_data")).get("PostPage"));
JSONObject mediaJO = (JSONObject) postPageJA.get(0);
JSONObject keyJO = (JSONObject) mediaJO.get("media");
String keyStr = (String) keyJO.get("key");

System.out.println("keyStr = "+keyStr);

这个有点复杂,而且还取决于你对JSON结构的了解。一种更简单的方法可能是使用正则表达式:

Pattern p = Pattern.compile(
    "media[\":\\s\\{]+key[\":\\s\\{]+\"([^\"]+)\"", 
    Pattern.DOTALL);
Matcher m = p.matcher(html);
if (m.find()){
    String keyFromRE = m.group(1);
    System.out.println("keyStr (via RegEx) = "+keyFromRE);  
}

关于android - 如何在android编程中使用jsoup从html获取此脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707679/

相关文章:

android - 按需显示/隐藏 Listview SectionIndex

安卓 : IllegalArgumentException: "Component class X does not exist" in API 17 (no crash in API 8)

java - 我应该为 tabhost 中的每个选项卡创建一个新的 Activity/xml 吗?

android - 无法解析 : junit:junit:4. 12

javascript - 有人可以解释为什么我的 javascript 不工作吗?

ios - 如何使用 UIWebview 删除 iOS 应用程序的 html5 本地存储

javascript - 访问 html 中的资源(图像等)

javascript - 如何打印json属性名称?

php - 在 PHP 中启用 json_encode

python - 在 Python 3.9 中使用 Pandas 将 Excel 转换为 JSON