How can I iterate through rows of web form using selenium?


Please I have a web form that I use selenium script to autofill in data row by row. Each time I run add_event_button, a new row is created, then I autofill the date_field to the remarks_field. All the fields within one row have similar ID attributes. The only difference is when you click the variable add_event_button, the new row has an ID increment of 1 across all fields.

Here is what I have done:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from import expected_conditions as EC
from import By
from import WebDriverWait
from import Select
import time
import pandas as pd
from time import sleep

add_event_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="tab-voyage-log-12780"]/div[2]/a[2]'))).click()

date_field = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#WGItem02_voyage_log-25_4')))

location_field = Select(driver.find_element(By.ID, 'WGItem09_voyage_log-2_4'))

event_field = Select(driver.find_element(By.ID, 'WGItem04_voyage_log-2_4'))

subevent_field = Select(driver.find_element(By.ID, 'WGItem05_voyage_log-2_4'))

remarks_field = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#WGItem06_voyage_log-2_4')))

How do I iterate through the above block of code to run up to 20 times. For example; WGItem05_voyage_log-2_4 will run till it stops at WGItem05_voyage_log-20_4 and remarks_field.send_keys(remarks_data_col[1]) runs till remarks_field.send_keys(remarks_data_col[20]).


for i in range(2,21):
    remarks_field = wait.until(EC.element_to_be_clickable((By.XPATH, f"//*[@id='WGItem06_voyage_log-{i}_4']")))

Did you mean looping it like so and using f string to access the element with that xpath.

Answered By – Arundeep Chohan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published