【问题标题】:Cant extract attribute from html response无法从 html 响应中提取属性
【发布时间】:2020-02-11 12:07:29
【问题描述】:

我正在尝试从 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 是存储为 String 的 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 但它给了我空指针异常

【问题讨论】:

    标签: java xml rest-assured


    【解决方案1】:

    要将完整的响应正文作为字符串,您需要使用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 在上面的示例中用于解析来自&lt;body&gt; 的文本。你可以在这里阅读更多相关信息 - https://github.com/FasterXML/jackson-databind

    【讨论】:

    • 谢谢,但无法获取上述 html 中属性的属性值“'abcd/12345'"out。{serviceUrl: 'abcd/12345', serviceTicket: 'ABCD-123-1271821818sdsdbbsdgw3-pas'}因为它没有将 serviceUrl 标识为属性。请在此处帮助我。
    • 有人能帮我用索引吗?
    • @aak 我已经用提取serviceUrl 值的例子更新了我的答案
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    相关资源
    最近更新 更多