简体   繁体   English

python2.7 - selenium 使用 for 循环查找元素

[英]python2.7 - selenium using for loop to find element

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.不过,我在使用 selenium 实现 for 循环时遇到了麻烦。

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.我有 python 2.7 并使用 chrome 作为我的浏览器。

I don't know what I'm doing wrong... Thank you in advance: )我不知道我做错了什么......提前谢谢你:)

The [i] would not auto-magically be replaced by the value of the i variable, you should "format" it into the string instead: [i]不会自动被i变量的值替换,您应该将其“格式化”为字符串:

for i in range(1, 6):
    browser.find_element_by_id("t_z12022421023027015111a68_b_{i}_r1".format(i=i)).send_keys(8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM