springboot发送http请求返回html

image.png
如图 springboot发送get请求 返回html 怎么接收html 并取其中特定参数

阅读 5.9k
3 个回答

为什么没有接口只有页面?在写爬虫?

  1. 如果页面足够简单,用正则扣也没什么问题,用RestTemplate直接拿String,自己解析
  2. 否则建议用jsoup,有各种选择器方便拿页面元素,比自己写正则稳妥很多
新手上路,请多包涵

以下代码发起 Http 请求

public static String doGet(String url) {  
    logger.info("当前请求URL{},请求方式为GET", url);  
    String result = null;  
    CloseableHttpResponse response = null;  
    try {  
        HttpGet httpGet = new HttpGet(url);   
        response = httpClient.execute(httpGet);  
        HttpEntity entity = response.getEntity();  
        if (entity != null) {    
            result = EntityUtils.toString(entity, "utf-8");  
        }  
    } catch (Exception e) {  
        logger.error("处理失败 {}", e.getMessage());  
        e.printStackTrace();  
    } finally {  
        if (response != null) {  
            try {  
                response.close();  
            } catch (IOException e) {  
                logger.error(e.getMessage());  
            }  
        }  
    }  
  return result;  
}

将结果转为 JSOUP, 具体要找哪些标签内的内容,可以看下 JSOUP 的文档

//第一步,将内容解析成一个Document类  
Document doc = Jsoup.parse(result);  
//第二步,根据我们需要得到的标签,选择提取相应标签的内容  
String title = doc.getElementsByTag("title").text();
//也可以使用select查询head中的标签
String image = doc.head().select("meta[property=og:image]").attr("content");

谢谢回答 已经搞定 jsoup真的好用

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题