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

无法从本地Jsoup文档解析数据到Team对象数组

本地HTML解析球队数据失败:无法创建Team对象

我正在做课程项目,要从本地HTML文档解析球队数据。能找到文档、定位元素,但转换为新Team对象时代码直接跳过,没创建任何对象。相关代码如下,求帮忙!

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.jsoup.nodes.Element;


public class Comparison {
    
    public void loadTeams() throws IOException {
    
        ArrayList<Team> NBA = new ArrayList<Team>(30);
        File localFile = new File("eclipse-workspace\\Capstone Project II\\src\\localTeamData\\Team_stats.html");
        Document nba = Jsoup.parse("localFile");            
        Elements team = nba.getElementsByAttributeValue("data-stat", "Team_Name");
        Elements shooting = nba.getElementsByAttributeValue("data-stat" , "Effective Field Goal");
        Elements turnovers = nba.getElementsByAttributeValue("data-stat" , "Turnover");
        Elements rebounds = nba.getElementsByAttributeValue("data-stat" , "Rebounding");
        Elements freethrows = nba.getElementsByAttributeValue("data-stat" , "Free Throw");

        for (int i = 0; i < team.size(); i++) {
            String name = team.get(i).text();
            double shootingScore = Double.parseDouble(shooting.get(i).text());
            double turnoversScore = Double.parseDouble(turnovers.get(i).text());    
            double reboundsScore = Double.parseDouble(rebounds.get(i).text());  
            double freethrowsScore = Double.parseDouble(freethrows.get(i).text());  
            NBA.add(new Team(name, shootingScore, turnoversScore, reboundsScore, freethrowsScore));
        }
//for testing//
for(int i=0; i<NBA.size(); i++) {
        System.out.print(NBA.getClass());
}
    }
}

问题分析与修复方案

核心错误点

  • Jsoup解析方式错误:你调用Jsoup.parse("localFile")时,是把字符串"localFile"当作HTML内容解析,而非读取你创建的localFile对象指向的本地文件。这导致解析出的文档是空的,所有Elements集合长度为0,循环根本不会执行。
  • 测试代码逻辑无效:System.out.print(NBA.getClass())只会输出ArrayList的类对象,就算NBA里有数据,也看不到具体的Team对象信息,无法验证创建是否成功。

修复步骤

  1. 修正本地文件解析代码
    将Document nba = Jsoup.parse("localFile");替换为:

    Document nba = Jsoup.parse(localFile, "UTF-8");
    

    这才是Jsoup读取本地HTML文件的正确方式,第二个参数指定文件编码,避免乱码。

  2. 完善测试代码
    把测试循环改为:

    for(int i=0; i<NBA.size(); i++) {
        System.out.println(NBA.get(i));
    }
    

    注意:需要在Team类中重写toString()方法,否则会打印对象的内存地址,无法看到具体数据。

  3. 额外检查项

    • 确认本地文件路径正确:如果用相对路径,要保证程序运行的工作目录是项目根目录;或者直接使用绝对路径(比如"C:\\xxx\\eclipse-workspace\\Capstone Project II\\src\\localTeamData\\Team_stats.html")。
    • 检查HTML元素数量:确保data-stat为Team_Name、Effective Field Goal等的元素数量一致,避免循环时出现IndexOutOfBoundsException。
    • 验证Team构造函数:确认Team类的构造函数能正确接收String和四个double类型的参数,没有参数类型不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:07:14