我需要在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 响应的数据额外字段。
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"。