JSoup在Android上的行为与在PC上的行为不同?

时间:2014-02-12 03:08:45

标签: java android jsoup

我一直在移植我为Android制作的PC应用程序。我有完整的代码和运行,但JSoup似乎由于某种原因得到错误的数据。我从工作的PC应用程序直接复制和粘贴,工作得很好。这是我在PC和Android中使用的一段代码

        String AllGamesURL = "http://www.nfl.com/standings?category=league&season=" + Stringyear + "-REG";
        String HomeGamesURL = "http://www.nfl.com/standings?category=league&season=" + Stringyear + "-REG&split=Home";
        String AwayGamesURL = "http://www.nfl.com/standings?category=league&season=" + Stringyear + "-REG&split=Road";
        String DivisionGamesURL = "http://www.nfl.com/standings?category=league&season=" + Stringyear + "-REG&split=Division";

        Document AllGames = Jsoup.connect(AllGamesURL).get();
        Document HomeGames = Jsoup.connect(HomeGamesURL).get();
        Document AwayGames = Jsoup.connect(AwayGamesURL).get();
        Document DivisionGames = Jsoup.connect(DivisionGamesURL).get();

        Elements AllGamesTeams = AllGames.select("table.data-table1 tr.tbdy1");
        Elements HomeGamesTeams = HomeGames.select("table.data-table1 tr.tbdy1");
        Elements AwayGamesTeams = AwayGames.select("table.data-table1 tr.tbdy1");
        Elements DivisionGamesTeams = DivisionGames.select("table.data-table1 tr.tbdy1");

        for (Element teamName : AllGamesTeams) {
            if(teamName.select("td[align] > a[href]").text().trim().equals("")) {
                team = teamName.select("td[align]").text().trim();
            } else {
                team = teamName.select("td[align] > a[href]").text().trim();
            }
            if(team.equals(currentSelectedTeam)) {
                //Division = teamName.select("td:eq(2)").text().trim();
                wins = Integer.parseInt(teamName.select("td:eq(3)").text().trim());
                losses = Integer.parseInt(teamName.select("td:eq(4)").text().trim());
                ties = Integer.parseInt(teamName.select("td:eq(5)").text().trim());
                gamesPlayed = wins + losses + ties;
                pointsFor = Integer.parseInt(teamName.select("td:eq(7)").text().trim());
                pointsAgainst = Integer.parseInt(teamName.select("td:eq(8)").text().trim());
                break;
            }
        }

在PC版上,它获得了胜利,损失等等,但在Android上,它获取了错误的数据。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

连接时传入特定的userAgent以请求站点的桌面版本而不是移动版本,例如:

Document AllGames = Jsoup.connect(AllGamesURL)
    .userAgent("Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36")
    .get();

为了确认,我也尝试了同样的事情但是传入了Android userAgent而且它检索了不同的内容(默认情况下这将在Android上发生)。

您可以使用我提供的代码,或在此处查看用户代理列表:http://www.useragentstring.com/pages/useragentstring.php