gpt4 book ai didi

java - 从具有特定类的页面的所有表格内的 标记中提取数据

转载 作者:行者123 更新时间:2023-12-02 07:21:26 25 4
gpt4 key购买 nike

我想从 url List of cities and towns in India 中提取所有城市名称和州名称使用 jsoup,下面给出了该页面的 HTML 代码片段。

这里 Abhaypuri 是城市名称,Assam> 是州名。此外,类似的城市和州名称在页面中多次出现,在这种出现数千次的表结构中,除了 td 标记内的 url 之外,所有内容都是相同的。

<table class="wikitable sortable" style="text-align:;">
<tr>
<th>Name of City/Town</th>
<th>Name of State</th>
<th>Classification<pre><code></th>
<th>Population (2001)<pre><code></th>
<th>Population (2011)<pre><code></th>
</tr>
<tr>
<td><pre><code><a href="/wiki/Abhayapuri" title="Abhayapuri">Abhayapuri<pre><code></a><pre><code></td>
<td><pre><code><a href="/wiki/Assam" title="Assam">Assam<pre><code></a><pre><code></td>

我是 jsoup 新手。任何帮助,将不胜感激。谢谢。

最佳答案

示例代码:

    Document root = Jsoup.parse(new URL("http://en.wikipedia.org/wiki/List_of_cities_and_towns_in_India"), 30000);
//find all tables
Elements tables = root.select("table");
for (int m = 0; m < tables.size(); m++) {
final Element table = tables.get(m);
Elements th0 = table.select("tbody tr th");
//find our tables
if (th0 != null && th0.get(0).text().trim().equals("Name of City/Town")) {
Elements es = table.select("tbody tr");
for (int i = 1; i < es.size(); i++) {
Elements td = es.get(i).select("td");
String city = td.get(0).select("a").first().text();
String state = td.get(1).select("a").first().text();
System.out.println(city + " => " + state);
}
}
}

输出:

Abhayapuri => Assam
Achabbal => Jammu and Kashmir
Achalpur => Maharashtra
Achhnera => Uttar Pradesh
Adari => Uttar Pradesh
Adalaj => Gujarat
Adilabad => Andhra Pradesh
Adityana => Gujarat
pereyaapatna => Karnataka
Adoni => Andhra Pradesh
Adoor => Kerala
Adyar => Karnataka
Adra => West Bengal
Afzalpura => Karnataka
Agartala => Tripura

关于java - 从具有特定类的页面的所有表格内的 <td> 标记中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14169446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com