Reputation: 77
I have a webpage HTML like this:
<table class="table_type1" id="sailing">
<tbody>
<tr>
<td class="multi_row"></td>
<td class="multi_row"></td>
<td class="multi_row">1</td>
<td class="multi_row"></td>
</tr>
<tr>
<td class="multi_row"></td>
<td class="multi_row"></td>
<td class="multi_row">1</td>
<td class="multi_row"></td>
</tr>
</tbody>
</table>
and tr tags are dynamic so i don't know how many of them exist, i need all td[3] of any tr tags in a list for some slicing stuff.it is much better iterate with built in tools if find_element(s)_by_xpath("")
has iterating tools.
Upvotes: 2
Views: 2715
Reputation: 8479
To get the 3 rd td of each row, you can try either with xpath
driver.find_elements_by_xpath('//table[@id="sailing"]/tbody//td[3]')
or you can try with css selector like
driver.find_elements_by_css_selector('table#sailing td:nth-child(3)')
As it is returning list you can iterate with for each,
elements=driver.find_elements_by_xpath('//table[@id="sailing"]/tbody//td[3]')
for element in elements:
print(element.text)
Upvotes: 1
Reputation: 193088
To print the text e.g. 1 from each of the third <td>
you can either use the get_attribute()
method or text
property and you can use either of the following solutions:
Using CssSelector and get_attribute()
:
print(driver.find_elements_by_css_selector("table.table_type1#sailing tr td:nth-child(3)").get_attribute("innerHTML"))
Using CssSelector and text
property:
print(driver.find_elements_by_css_selector("table.table_type1#sailing tr td:nth-child(3)").text)
Using XPath and get_attribute()
:
print(driver.find_elements_by_xpath('//table[@class='table_type1' and @id="sailing"]//tr//following::td[3]').get_attribute("innerHTML"))
Using XPath and text
property:
print(driver.find_elements_by_xpath('//table[@class='table_type1' and @id="sailing"]//tr//following::td[3]').text)
Upvotes: 1
Reputation: 52665
Try
cells = driver.find_elements_by_xpath("//table[@id='sailing']//tr/td[3]")
to get third cell of each row
Edit
For iterating just use a for loop:
print ([i.text for i in cells])
Upvotes: 1
Reputation: 1184
Try following code :
tdElements = driver.find_elements_by_xpath("//table[@id="sailing "]/tbody//td")
Edit : for 3rd element
tdElements = driver.find_elements_by_xpath("//table[@id="sailing "]/tbody/tr/td[3]")
Upvotes: 1