【问题标题】:How to get this script from html with jsoup in android programming如何在android编程中使用jsoup从html获取这个脚本
【发布时间】:2016-02-15 21:59:31
【问题描述】:

我想用 jsoupscript 从 html 页面获取字符串值。但是也有一些问题:

  1. 该页面中有六个 scipt。我想用 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>

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

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

【问题讨论】:

  • 请提供网站链接,以便我为您检查问题

标签: android html json jsoup


【解决方案1】:

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);  
}

【讨论】:

  • 非常感谢。老实说,我想从 Instagram 页面获取“标题”。请看一下并告诉我这样做的最佳方法是什么。请将此行粘贴到 google chrome 中:view-source:instagram.com/p/m7SaJFIhyB
  • “标题”?我不明白您需要提取什么信息。只要修改我的方法,你应该没问题。
  • 感谢您的赞赏。 OP似乎对此有点迷失:)
  • 非常感谢!有用。是的!你是对的!我迷路了!但我有一个小问题,我不知道如何制作图案。能介绍一个好的训练源吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多