栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用JSoup从表中提取数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用JSoup从表中提取数据

这是一些示例代码,您如何仅选择标题:

Element tableHeader = doc.select("tr").first();for( Element element : tableHeader.children() ){    // Here you can do something with each element    System.out.println(element.text());}

你得到

document

  1. 解析 文件

    document doc = Jsoup.parse(f, null);
    (这里
    f
    File
    null
    字符集,请参阅jsoup对铁道部的相关信息文件)

  2. 解析 网站 :(

    document doc = Jsoup.connect("http://your.url.here").get();
    不要错过
    http://

输出:

Kl.Std.LehrerFachRaumVLehrerVFachVRaumInfo

现在,如果需要

List
所有条目的数组(或更好的数组),则可以创建一个新类,用于存储每个条目的所有信息。接下来,您通过jsoup解析HTML,并填充该类的所有字段并将其添加到列表中。

// Note: all values are strings - you'll need to use better types (int, enum whatever) here. But for an example its enough.public class Entry{    private String klasse;    private String stunde;    private String lehrer;    private String fach;    private String raum;    private String vLehrer;    private String vFach;    private String vRaum;    private String info;    // constructor(s) and getter / setter    }

接下来,代码将填充您的条目(包括存储它们的列表):

List<Entry> entries = new ArrayList<>();        // All entries are saved hereboolean firstSkipped = false;        // Used to skip first 'tr' tagfor( Element element : doc.select("tr") )       // Select all 'tr' tags from document{     // Skip the first 'tr' tag since it's the header    if( !firstSkipped )    {        firstSkipped = true;        continue;    }    int index = 0;        // Instead of index you can use 0, 1, 2, ...    Entry tableEntry = new Entry();    Elements td = element.select("td");         // Select all 'td' tags of the 'tr'    // Fill your entry    tableEntry.setKlasse(td.get(index++).text());    tableEntry.setStunde(td.get(index++).text());    tableEntry.setLehrer(td.get(index++).text());    tableEntry.setFach(td.get(index++).text());    tableEntry.setRaum(td.get(index++).text());    tableEntry.setvLehrer(td.get(index++).text());    tableEntry.setvFach(td.get(index++).text());    tableEntry.setInfo(td.get(index++).text());    entries.add(tableEntry);         // Finally add it to the list}

如果您在第一篇文章中使用html,则会得到以下输出:

[Entry{klasse= , stunde=4, lehrer=Méta, fach=HU, raum= , vLehrer=Shne, vFach= , vRaum=null, info= }]

注意:
我只是用于

System.out.println(entries);
此目的。因此,输出的格式来自的
toString()
方法
Entry


请参阅Jsoup文档,尤其是有关jsoup选择器api的文档。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号