【问题标题】:Trouble parsing table class with href in Jsoup在 Jsoup 中使用 href 解析表类时遇到问题
【发布时间】:2015-12-30 06:47:04
【问题描述】:

我对 JSOUP 很陌生,才用了几天,主要是从这个网站学习。现在我正在尝试从以下 HTML 中获取一些信息:

        <td class="day no-repetition">Sun</td>
        <td class="full-date" nowrap="nowrap">17/05/15</td>
        <td class="competition"><a href="/national/england/premier-league/20142015/regular-season/r25191/" title="Premier League">PRL</a></td>

          <td class="team team-a ">
              <a href="/teams/england/sunderland-association-football-club/683/" title="Sunderland">
                Sunderland
              </a>
          </td>

        <td class="score-time score">
          <a href="/matches/2015/05/16/england/premier-league/sunderland-association-football-club/leicester-city-fc/1704225/" class="result-draw">           
            0 - 0
          </a>
        </td>
          <td class="team team-b ">
            <a href="/teams/england/leicester-city-fc/682/" title="Leicester City">
              Leicester City
            </a>
          </td>
        <td class="events-button button first-occur">
        </td>

          <td class="info-button button">

              <a href="/matches/2015/05/16/england/premier-league/sunderland-association-football-club/leicester-city-fc/1704225/" title="More info">More info</a>

          </td>

我需要从上面提取主队、得分和客队,但是我目前遇到了问题。我需要链接和文本本身。以下是我的代码:

     try {
        Document doc = Jsoup.connect(URL).get();
        Element table = doc.select("table[class=matches]").first();
        Elements rows = table.select("tr");
        for (int i=0; i<rows.size(); i++){
            Element row = rows.get(i);
            Elements data = row.select("td[class=team.team-a]");

            System.out.println(data.text());

        }


    } catch (IOException e) {
        e.printStackTrace();
    }

到目前为止,这还没有奏效。我尝试了“team.team-a”、“team.team.a”和它的所有其他变体。我设法获得了“竞争”类中的数据,当我将 ("td[class=team.team=a]") 替换为 (td[class=competition]) 时,它可以工作,但这不适用于任何有链接的类。

我们将不胜感激!

【问题讨论】:

    标签: java parsing html-parsing jsoup


    【解决方案1】:

    只需用一个点分隔多个类:

    td.team.team-a > a  // first team
    td.team.team-b > a  // second team
    td.score > a  // score
    

    【讨论】:

    • 似乎我错过了“td”。在前面。菜鸟的错误,我猜。谢谢!
    • 抱歉重复评论,但上面让我知道了团队本身的名称 - 我将如何获取链接本身? ? 内的位
    • @Axotic,你可以做类似doc.select("td.team.team-a &gt; a").first().attr("href")的事情。
    • @JonasCz 这绝对让生活更轻松,哈哈。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多