Search code examples
pythonseleniumhtml-tableiteratoriteration

Python Selenium table iteration not working


I'm fairly new in Python Selenium, and I'm trying to automate some webscraping in an iframe. I'm trying to get into a table (inside of the iframe) and click on a link. All is working fine but when referencing a table column the code seems to stick to the first column's value in every iteration. Here's some of my code:

1 table = driver.find_element_by_xpath("//table[@class='table table-striped v-align-middle']")
2 rows = table.find_elements_by_css_selector("tr")
3 for row in rows:
4     print(row.text)
5     print(row.find_element_by_xpath("//td[3]").text)
6     row.find_element_by_xpath("//td[6]//a[@href]").click()

Line 4 gets me the whole text of every line, perfectly working. This is just a test line. Line 5 gets me the 3rd column value of the first row every time. So not working. Line 6, just like Line 5, clicks on the link in column 6 but of the first row every time. So again, not working

I reckon there must be something on the xpath I'm not doing correctly? Thanks!

I really don't get why line 4 iterates fine but line 5 and 6 stick to the first column's value every time.


Solution

  • When using XPath and starting a search from a given element, you must add a . at the start of the locator, e.g.

    print(row.find_element_by_xpath(".//td[3]").text)
                                     ^ note the period