我想从 html 页面的 script 和 jsoup 获取字符串值。但也存在一些问题:
- 该页面中有六个脚本。我想用 jsoup 选择 forth of all(我的意思是数字 4)。我不知道我该怎么做。
- 该脚本中有一个键,我想捕获该键的值
在这里你可以看到想要的脚本:
<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/