我需要从列表标签内的 json 脚本获取数据



我需要在li标签中获取 Json 变量值,就像numberOfRecommendations一样3

<li data-extra="{&quot;hook&quot;:&quot;LFWB Hypertension&quot;,&quot;text&quot;:&quot;This patient does not have Diabetes.  There we can treat with a calcium-channel blocker.&quot;,&quot;type&quot;:&quot;detail&quot;,&quot;source&quot;:{&quot;label&quot;:&quot;{&quot;orgName&quot;:&quot;Liver Foundation&quot;,&quot;cdsCardId&quot;:3,&quot;cardName&quot;:&quot;This patient does not have Diabetes.  There we can treat with a calcium-channel blocker.&quot;,&quot;author&quot;:&quot;Dr. Abhishek Das&quot;,&quot;ifRecommendedByCurrentUser&quot;:true,&quot;ruleName&quot;:&quot;Systolic Blood Pressure greater than 140 without Diabetes History&quot;,&quot;serviceName&quot;:&quot;LFWB Hypertension&quot;,&quot;numberOfRecommendations&quot;:3,&quot;uuid&quot;:&quot;219470ab-37a9-4fac-94b0-09cb34fb4e19&quot;}&quot;}}" 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 响应的数据额外字段。

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"。

最新更新