java - 如何在使用 Spring Boot 访问一个网站时获取 html 代码并将整个 HTML 数据存储在一个字符串变量中?
问题描述
我试图找到一些关于如何在使用 Spring Boot 访问任何网站时获取 HTML 数据的内容,但我没有得到任何最好的示例内容。有人可以帮我解决这个问题吗?
解决方案
例如,您可以使用 HTML 解析器JSoup
来执行此操作。
演示:
import java.io.IOException;
import org.jsoup.Jsoup;
public class JSoupDemo {
public static void main(String[] args) throws IOException {
String webPage = "http://www.example.com";
String html = Jsoup.connect(webPage).get().html();
System.out.println(html);
}
}
输出:
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
div {
margin: 0 auto;
width: auto;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
或者,您可以使用java.io.BufferedReader
以下方法进行操作:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new URL("http://www.example.com").openStream()))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐阅读
- c++ - 即使声明了符号,架构 x86_64 的未定义符号
- java - 鉴于我有同一个网卡的多个 ip,如何在 java 中通过特定的网卡 ip 发送请求
- python - 包含多个字符串的列表到 excel 文件
- c# - 如何使用 OLEDB 读取 xls 文件?
- c# - 如何在具有相同架构的两个 MSSQL 数据库之间进行查询并在实体框架中合并结果
- php - Eloquent 错误地将多个模型保存到数据库
- c# - 如何使用asp.net c#将分页添加到父gridview?
- java - 如何使用 spring data jpa 返回该日期的日期和记录数?
- asp.net-web-api - 在方法 POST 中接收数据和文件
- python - 使用 pandas 从 Excel 文件中读取最后一列