【问题标题】:Form filling automation: Why is send_keys filling in more than one field automatically?表单填写自动化:为什么 send_keys 会自动填写多个字段?
【发布时间】:2020-04-27 10:41:32
【问题描述】:

我在 Windows 中使用 Python 和 Selenium 编写以下内容,目的是在两个字段中填写当前日期和每个字段的指定时间:

#Defines and inputs date and time into End Time field 
x = datetime.datetime.now()
endtime = x.strftime("%m/%d/%Y" " 8:30 AM")
endtime_field = driver.find_element_by_xpath('//*[@id="MainContent_endDt"]')
endtime_field.send_keys([endtime])

#Defines and inputs date and time into Start Time field 
starttime = x.strftime("%m/%d/%Y" " 8:28 AM")
starttime_field = driver.find_element_by_xpath('//*[@id="MainContent_startDt"]')
starttime_field.send_keys([starttime])

当我在Chrome浏览器中运行该文件时,endtime_field 填写正确,但starttime_field 自动填写了结束时间和开始时间的条目,没有空格,即:

04/27/2020 8:30 AM04/27/2020 8:28 AM

似乎 endtime_field.send_keys 在第二个字段中自动运行,即使它具有不同的 XPath。我注意到endtime 的 AM 之后和starttime 的 04 之前没有空格。

我尝试使用Keys.TABendtime_field 移动到starttime_field,并在填写之前执行starttime_field.clear(),但它们都不起作用。

这是使用浏览器检查时starttime_field 元素的样子:

<input name="ctl00$MainContent$startDt" type="text" id="MainContent_startDt" class="form-control">

任何帮助将不胜感激。

【问题讨论】:

  • 这段代码上面是否有任何循环或条件语句。当您选择相同的值时,您是否检查了应用程序在没有自动化的情况下的行为?

标签: python forms selenium automation


【解决方案1】:

send_keys 方法的工作方式类似于手动输入,它不考虑当前焦点或选择上下文。 在您的情况下,在刷新/写入一个控件中的所有字符之前,焦点似乎转移到了另一个控件。

来自 python selenium 文档:

send_keys(*keys_to_send)
Sends keys to current focused element.
Args:   
keys_to_send: The keys to send. Modifier keys constants can be found in the ‘Keys’ class.

send_keys_to_element(element, *keys_to_send)
Sends keys to an element.
Args:   
element: The element to send keys.
keys_to_send: The keys to send. Modifier keys constants can be found in the ‘Keys’ class.

【讨论】:

  • 是的,似乎第一个 send_keys 还没有停止。您能否详细说明如何结束第一个控制?谢谢
  • 你可以在最后一行的send_keys之前使用starttime_field.click()。
  • 效果很好——谢谢!只是为了我的学习——这个点击完成'endtime_field.send_keys([endtime])'对吗?按照这个逻辑,在下一步之前我是否需要在某个地方做一个新的“click()”?
  • 是的,如果您使用 send_keys(*keys_to_send) 方法,则需要使用 click() 移动当前焦点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 2011-07-10
  • 2013-07-30
  • 2023-04-09
  • 1970-01-01
  • 2018-10-26
  • 2012-04-21
相关资源
最近更新 更多