我需要在 li
标记内获取 Json 变量值,例如 numberOfRecommendations
,即 3
<li data-extra="{"hook":"LFWB Hypertension","text":"This patient does not have Diabetes. There we can treat with a calcium-channel blocker.","type":"detail","source":{"label":"{\"orgName\":\"Liver Foundation\",\"cdsCardId\":3,\"cardName\":\"This patient does not have Diabetes. There we can treat with a calcium-channel blocker.\",\"author\":\"Dr. Abhishek Das\",\"ifRecommendedByCurrentUser\":true,\"ruleName\":\"Systolic Blood Pressure greater than 140 without Diabetes History\",\"serviceName\":\"LFWB Hypertension\",\"numberOfRecommendations\":3,\"uuid\":\"219470ab-37a9-4fac-94b0-09cb34fb4e19\"}"}}" style="" xpath="1">This patient does not have Diabetes. There we can treat with a calcium-channel blocker.<br><label style="color: white; font-weight: normal;">aaaa</label><label style="color: grey; float: right; font-weight: normal;">Dr. Abhishek Das, LFWB Hypertension</label><label style="color: white; font-weight: normal; float: right;">---</label><label style="color: rgb(30, 136, 229); float: right; font-weight: normal;">3 </label><img src="resources/images/headshots/recommended.png" width="15" height="15" style="border-radius: 50%; display: inline-block; margin-right: 5px; float: right;"></li>
最佳答案
请找到下面的代码,这将帮助您获取属性“data-extra”,并从中提取您想要的任何字段。
第 1 步: 获取包含 JSON 响应的 data-extra 字段。
String jsonStr = driver.findElement(By.tagName("li")).getAttribute("data-extra");
System.out.println(jsonStr);
第 2 步: 现在我们需要清理 JSON 响应,因为它包含额外的反斜杠和双引号。
String jsonFormattedString = jsonStr.replaceAll("\\\\", "");
jsonFormattedString = jsonFormattedString.replace("\"{", "{");
jsonFormattedString = jsonFormattedString.replace("\"}}", "}}");
System.out.println(jsonFormattedString);
第 3 步: 现在我们需要解析 JSON 并从 JSON 响应中提取 numberOfRecommendations 键字段。
JSONObject jsonObject = new JSONObject(jsonFormattedString);
JSONObject source = jsonObject.getJSONObject("source");
JSONObject label = source.getJSONObject("label");
int numberOfRecommendations = label.getInt("numberOfRecommendations");
System.out.println(numberOfRecommendations);
注意:由于您没有提到完整的HTML,我假设tagName字段为“li” ”。
关于java - 我需要从列表标签内的 json 脚本获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57653746/