目標:https://fa.163.com/zx/gjs/1/ (網易貴金屬資訊列表)
.g-newsdl 標籤dl > aspan.f-frspan.f-fl.f-ofe.u-digest

public class StockUtils {
public static String getHtmlByUrl(String url) throws IOException {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet get = new HttpGet(url);
HttpResponse resp = client.execute(get);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = resp.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
} catch (Exception e) {
System.err.println("訪問異常: " + url);
e.printStackTrace();
}
return null;
}
}
public class StockTest {
public static void main(String[] args) throws IOException {
String html = StockUtils.getHtmlByUrl("https://fa.163.com/zx/gjs/1/");
parserHtml(html);
}
public static void parserHtml(String html) {
Document doc = Jsoup.parse(html);
Elements items = doc.getElementsByClass("g-news").select("dl");
for (Element item : items) {
String title = item.select("a").text();
String link = item.select("a").attr("href");
String time = item.select("span.f-fr").text();
String summary = item.select("span.f-fl.f-ofe.u-digest").text();
System.out.println("標題: " + title);
System.out.println("鏈接: " + link);
System.out.println("時間: " + time);
System.out.println("摘要: " + summary);
System.out.println("=================================");
}
}
}

CloseableHttpClient、配置 PoolingHttpClientConnectionManagerHttpAsyncClient 或 CompletableFuture + 線程池<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.15.4</version>
</dependency>
源碼下載:百度網盤 | 作者博客:cnblogs.com/clayzhang