【问题标题】:Extracting data from <td> tags inside all tables of a page with certain class从具有特定类的页面的所有表中的 <td> 标记中提取数据
【发布时间】:2012-12-19 14:49:42
【问题描述】:

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

这里 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 的新手。任何帮助,将不胜感激。谢谢。

【问题讨论】:

    标签: java html-parsing jsoup


    【解决方案1】:

    示例代码:

        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
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多