如何使用Python Selenium在输入字段中输入数值?

问题描述 投票:1回答:1

我有一个脚本将值写入网页,并且所有值都写入,除了一个字段不断抛出以下错误:enter image description here(屏幕快照提供了b / c的其他类似问题,许多评论说这不可能在网页上发生。)“请输入一个数字值。”

这是我的代码:

workcenter_to_add = {}
workcenter_to_add['BatchCycle'] = str(2.78)
# driver = my_chrome_webpage
WebDriverWait(driver, wait_time).until(EC.presence_of_element_located((By.XPATH, "//input[@id='BatchSize']"))).send_keys(workcenter_to_add['BatchCycle'])

[众所周知,如果我没有输入2.78值,因为string WebDriver会引发错误。但是我的页面需要一个数值。我被卡住了。

我已经在Google周围搜索,但没有找到可用的答案。看来,如果您使用的是Java,则可以使用setAttribute的方法,但是如果您使用的是Python,则必须弄清楚一些事情。

例如,问题here看起来很有希望,但我找不到String或如何导入它才能使其正常工作。还有其他一些关于执行java的较老的问题,但我没有运气让它们工作。

我在这里有页面源HTML:https://drive.google.com/open?id=1xRNPfc5E65dbif_44BQ_z_4fMYVJNPcs

python selenium webdriverwait expected-condition constraint-validation
1个回答
1
投票
我确定虽然您传递的是.send_keys('2.78')值,但该值仍然是数字。因此,理想情况下,您不应遇到此问题。

这里是示例html和脚本,用于确认相同。

<html><head> <script> function validateOnClick(evt) { var theEvent = evt || window.event; // Handle paste if (theEvent.type === 'click') { key = document.querySelector('input').value.toString(); } else { // Handle key press var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode(key); } var regex = /[0-9]|\./; console.log(key); if( !regex.test(key) ) { alert("Please enter numeric value"); theEvent.returnValue = false; if(theEvent.preventDefault) theEvent.preventDefault(); } } </script> </head> <body> <input placeholder='check'></input> <button type='submit' onClick='validateOnClick(event)'>Submit</button> </body></html>
检查脚本:

driver.get(url) # check with string (not integer) driver.find_element_by_tag_name('input').send_keys('Hello') driver.find_element_by_tag_name('button').click() print(driver.switch_to.alert.text) driver.switch_to.alert.dismiss() # now check with integer driver.find_element_by_tag_name('input').clear() driver.find_element_by_tag_name('input').send_keys(workcenter_to_add['BatchCycle']) driver.find_element_by_tag_name('button').click()

截屏:enter image description here

因此,我们必须检查实现的js /方法是什么,以验证在字段中输入的值。如您所见,从python脚本传递带引号的整数对字段及其数据类型没有任何区别。

0
投票
带有通知的对话框

“

可能是Constraint API's element.setCustomValidity()方法的结果。


我经历过您共享的element.setCustomValidity()。但是根据您的代码试用:

page-source HTML

我在页面源中没有找到任何By.XPATH, "//input[@id='BatchSize']"
标签。基于文本的相关HTML本可以帮助我们更好地构建答案。但是,您需要考虑以下几点:

    [当您处理<input>标签时,应使用<input>而不是presence_of_element_located()
  • 如果您没有将element_to_be_clickable()值输入为字符串,则不会告诉我们WebDriver引发的错误。不过,由于2.78有效,因此您可以坚持使用。
  • 有效地,您的代码行将是:

    str(2.78)


参考

您可以在workcenter_to_add = {} workcenter_to_add['BatchCycle'] = str(2.78) WebDriverWait(driver, wait_time).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='BatchSize']"))).send_keys(workcenter_to_add['BatchCycle']) 中找到一些相关的讨论:

© www.soinside.com 2019 - 2024. All rights reserved.