1

I'm trying to create a script to automatically fill in timecard for my work. I'm having trouble implementing for loop with selenium though.

For example, i have these many lines:

    browser.find_element_by_id("t_z12022421023027015111a68_b_1_r1").send_keys(8)
    browser.find_element_by_id("t_z12022421023027015111a68_b_2_r1").send_keys(8)
    browser.find_element_by_id("t_z12022421023027015111a68_b_3_r1").send_keys(8)
    browser.find_element_by_id("t_z12022421023027015111a68_b_4_r1").send_keys(8)
    browser.find_element_by_id("t_z12022421023027015111a68_b_5_r1").send_keys(8)

and I would like to shorten them:

for i in range(1, 6):
    browser.find_element_by_id("t_z12022421023027015111a68_b_[i]_r1").send_keys(8)

However, I get this error message:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element

Could someone please help? I have python 2.7 and use chrome as my browser.

I don't know what I'm doing wrong... Thank you in advance! :)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • This should instead be a duplicate of https://stackoverflow.com/questions/2960772/how-do-i-put-a-variable-s-value-inside-a-string, but I don't have a dupe hammer since the question was originally tagged differently. – Karl Knechtel Jul 27 '22 at 03:57

1 Answers1

1

The [i] would not auto-magically be replaced by the value of the i variable, you should "format" it into the string instead:

for i in range(1, 6):
    browser.find_element_by_id("t_z12022421023027015111a68_b_{i}_r1".format(i=i)).send_keys(8)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195