Reputation: 11
HTML:
<div class="attach">
<app-table>
<table class="table"> //
<thead>
<tr>
<th><span>Name</span></th>
<th><span>Address</span></th>
</tr>
</thead>
<tbody>
<tr>
<td>aaa</td>
<td>bbb</td>
</tr>
<tr>
<td>aaa111</td>
<td>bbb222</td>
</tr>
</tr>
</tbody>
</table>
</app-table>
</div>
The page may have multiple web tables. However, parent element "attach" is unique for this table. How can I count the total number of rows and columns? I found lot of info online but I could not fix it.
Upvotes: 0
Views: 2467
Reputation: 1
We can resolve this in Java Language as follows:
List rows=driver.findElements(By.xpath("//div[@class="attach"]//tbody//tr"));
int rowCount=rows.size();
List columns=driver.findElements(By.xpath("//div[@class="attach"]//table//th"));
int columnCount=columns.size();
Upvotes: 0
Reputation: 1938
You have include the class name in the xpath to make it unique in your case.
#Number of columns in the table
cols = driver.find_elements_by_xpath("//div[@class="attach"]//table/thead//th")
print(cols)
#Number of rows in the table
rows = driver.find_elements_by_xpath("//div[@class="attach"]//table/tbody//tr")
print(rows )
Upvotes: 1
Reputation: 2485
from www.tutorialspoint.com/how-to-count-the-number-of-rows-in-a-table-in-selenium-with-python:
# identifying the number of rows having <tr> tag
rows = driver.find_elements_by_xpath("//table/tbody/tr")
# len method is used to get the size of that list
print(len(rows))
#to close the browser
driver.close()
Number of cells may vary per row. But you can use xpath to count those too:
row1 = driver.find_elements_by_xpath("//table/tbody/tr")
cols = row1.find_elements_by_xpath("//td")
print(len(cols))
Upvotes: 1