'Selenium, Python - Use For-loop in finding values in a column, but resulted in duplicating first values instead
Above is the practice website I am attempting to extract only the name column. However, from my For-loop, I am repeatedly accounting the name Alan five times (see img below). Unfortunately, my For-loop counted the header row too as row 0.
Code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#Scenario a HTML table is provided
#Feature: HTML table
def test_table():
URL = 'https://testpages.herokuapp.com/styled/tag/table.html'
#Given website loaded a table <--The Set Up
b=webdriver.Chrome()
b.get(URL)
wait=WebDriverWait(b,20)
#When user arrives at the website and sees a table <-- IGNORE, when print text, all values are correct.
table=b.find_element(By.ID,'mytable')
#Then the table shows a column of names <-- The issue
rows=b.find_elements(By.TAG_NAME,'tr')
for i, col in enumerate(rows):
col=b.find_element(By.TAG_NAME,'td').text
print(f'Row: {i}, Name: {row}')
b.quit()
test_table()
Result:
I had thought of using the expected condition, but the table is static. Which led to me deciding that the use of expected condition wasn't necessary. Also, I had considered that the tag name wasn't used correctly, but this wasn't the case. Any assistant is appreciated.
Solution 1:[1]
You are traversing the whole page instead of just the rows. And since you are searching for single element in the loop, it returns the first td element of the page. It should be
for i, col in enumerate(rows):
name = col.find_element(By.TAG_NAME,'td').text
print(f'Row: {i}, Name: {name}')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Madhan S |


