You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jsoup从Yahoo Finance表格中提取股票代码?

问题分析与解决

错误原因

  1. CSS选择器语法错误:table.W(100%) tr中的括号()是CSS选择器的特殊字符,未转义导致Jsoup无法解析,触发SelectorParseException。
  2. 冗余且错误的类选择器:你使用的超长类选择器不仅冗余,而且Java字符串中的反斜杠转义错误(单反斜杠无法正确转义,需用双反斜杠),同时这类动态生成的复合类名稳定性差,页面更新后容易失效。

修正方案

步骤1:修复表格行选择器

将table.W(100%) tr改为以下两种写法之一:

  • 用属性选择器匹配完整类名:table[class="W(100%)"] tr
  • 转义特殊字符(Java中需双反斜杠):table.W\\(100%\\) tr

步骤2:简化股票代码选择器

Yahoo Finance的热门股票表格中,股票代码位于每行的第一个<td>内的<a>标签中,直接用.simpTblRow td:first-child a即可精准定位,无需复杂的复合类名。

修正后的完整代码

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.util.Arrays;

public String[] getTrendingTickers() {
    String[] trendingTickers = new String[30];
    int numTickers = 0;
    String url = "https://finance.yahoo.com/trending-tickers/";
    try {
        Document document = Jsoup.connect(url).get();
        // 匹配表格并筛选数据行(排除表头)
        for (Element row : document.select("table[class=\"W(100%)\"] tr.simpTblRow")) {
            // 提取第一个td中的股票代码文本
            String ticker = row.select("td:first-child a").text();
            if (!ticker.isEmpty()) {
                trendingTickers[numTickers] = ticker;
                numTickers++;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 返回仅包含有效数据的数组
    return Arrays.copyOf(trendingTickers, numTickers);
}

额外优化

  • 直接筛选tr.simpTblRow排除表头行,避免处理空数据。
  • 增加非空判断,防止无效内容存入数组。
  • 用Arrays.copyOf截取有效数据长度,减少空元素。

内容的提问来源于stack exchange,提问作者user15224296

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:10:49