问题
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