Using JSoup to get data-code value of a table

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 11:43:02

问题


How would I be able to use JSoup to get the data-code value from a table row?

Here is what I have tried but it just prints nothing:

Document doc = Jsoup.connect("http://www.example.com").get();
Elements dataCodes = doc.select("table[class=team-list]");

for (Element dataCode : dataCodes)
{
    System.out.println(dataCode.attr("data-code"));
}

The HTML code looks like this:

<body>
<div id-=""main">
    <div id="inner">
        <div id="table" class="scores-table">
            <table class ="team-list">
                <tbody>

                <tr data-code="1" class="data odd"></tr>
                <tr data-code="2" class="data even"></tr>
                <tr data-code="3" class="data odd"></tr>
                <tr data-code="1" class="data even"></tr>       

                </tbody>
            </table>
        </div>
    </div>
</div>

I want it to print out the data-code value on each row of the table (which is the team number).


回答1:


Your selector should go down to tr elements:

Elements dataCodes = doc.select("table.team-list tr");

According to the comments, this still results into an empty list - in this case, the table is probably dynamically generated with the help of javascript logic or a separate AJAX request.

In this case, one of the possible approaches would be to have a real browser handle that dynamic javascript, AJAX part. Try selenium browser automation framework:

WebDriver driver = new FirefoxDriver();
driver.get("http://www.example.com");

List<WebElement> elements = driver.findElements(By.cssSelector("table.team-list tr"));

for(WebElement element: elements)
{
    System.out.println(element.getAttribute('data-code'));
}


来源:https://stackoverflow.com/questions/28622487/using-jsoup-to-get-data-code-value-of-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!