无法从 html 响应中提取属性

Cant extract attribute from html response

我正在尝试从 html 响应中提取属性。

<html>
<head></head>
<body>
<script type="text/javascript" src="/sso/js/jquery/1/jquery.min.js?20190218"></script>
{serviceUrl: 'https://abcd/12345', serviceTicket: 'ABCD-123-1271821818sdsdbbsdgw3-pas'}
</body>
</html>

Web 服务的响应给了我上面的 html 响应,我想从中提取 serviceUrl 属性的值,但它给了我空指针异常。在下面的代码中,res 是存储为字符串的 html 响应。

Response res =  given()
    .queryParam("logintoken", logintoken)
    .when()
    .get("/sso/login")
    .then().assertThat().statusCode(200).extract().response();

Document doc = Jsoup.parse(res.toString());
Element link = doc.select("script").first();
String serviceUrl = link.attr("serviceUrl");
System.out.println(serviceUrl);

我希望最后一条语句中的 serviceUrl 能把我带回来 https://abcd/12345 但它给了我空指针异常

要获取字符串形式的完整响应正文,您需要使用 asString() 方法而不是 toString()。这是一个例子:

Response response =  given()
    .queryParam("logintoken", logintoken)
    .when()
    .get("/sso/login")
    .then().assertThat().statusCode(200).extract().response();

//Extract response body as a string
String html = response.asString();

//Parse extracted html with Jsoup
Document document = Jsoup.parse(html);

//Get <body> element from html
Element body = document.body();

//Extract text from <body> element
String bodyText = body.ownText();

//Parse extracted text using Jackson's ObjectMapper
Map<String, Object> map = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();

//Configure Jackson to work with unquoted fields and single quoted values
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

try {
  map = mapper.readValue(String.valueOf(bodyText), new TypeReference<Map<String, Object>>() {});
} catch (Exception e) {
  e.printStackTrace();
}

System.out.println(map.get("serviceUrl"));

上例中使用了 Jackson 的 ObjectMapper 来解析来自 <body> 的文本。您可以在此处阅读更多相关信息 - https://github.com/FasterXML/jackson-databind