【问题标题】:Setting value for input element in selenium Python在 selenium Python 中设置输入元素的值
【发布时间】:2019-01-01 20:47:16
【问题描述】:

我正在尝试更改输入标记元素的值。

这里是标签:<input type="hidden" id="hiRequestAccessType" data-bind="value: requestAccessTypeStr" value="2">

我想将值更改为“2,1”。

根据Set value of input instead of sendKeys() - selenium webdriver nodejs 的讨论,我尝试使用execute_script,但值保持不变。

我试过了:

passwordcheck_input_element = driver.find_element_by_xpath('//*[@id="hiRequestAccessType"]') . ###THIS DOESNT THROW ERRORS
new_value = "2,1"

driver.execute_script("arguments[0].value = arguments[1].toString()", passwordcheck_input_element, new_value)
# driver.execute_script("arguments[0].value = '" + new_value + "'", passwordcheck_input_element) . ###TRIED THIS IN LIEU OF ABOVE

对于任一替代方案,代码都会运行,但目视检查的值保持不变。我还尝试了使用 'setAttribute' 而不是直接使用上述两种替代方法,结果相同(无变化)。

请注意,该网页是一种表单,单击复选框可根据需要将值更改为“2,1”。 (但如果我尝试找到复选框元素,我会收到消息它不可点击,因此这条路线)。

现在,奇怪的是我知道它正在幕后做某事,因为我尝试在调用 execute_script 之前和之后查询 value 属性,它会为后者正确打印出新值。但是,正如我所说,UI 没有显示这种变化;此外,当我继续往下点击提交按钮时,会使用旧值,因为如果使用了新值,我没有得到应该加载的页面。

【问题讨论】:

    标签: python selenium input


    【解决方案1】:

    你能试试下面的代码吗?

    passwordcheck_input_element = driver.find_element_by_id("hiRequestAccessType")
    driver.execute_script("arguments[0].value = '2,1';", passwordcheck_input_element) 
    

    如果复选框对象不可点击,您也可以通过 javascript 执行来控制复选框对象。

    driver.execute_script("document.getElementById('hiRequestAccessType').checked = true;")
    

    【讨论】:

    • selenium.common.exceptions.WebDriverException: Message: unknown error: input_value is not defined
    【解决方案2】:

    driver.find_element_by_xpath('//*[@id="hiRequestAccessType"]').setAttribute("value", "1")

    简短地说,您可以在选择后使用 xpath 或 css 名称元素进行选择,您可以使用 .setAttribute 函数更改您的值。您还可以使用 getAttribute 函数获取当前选定的元素值。对于模拟复选框单击:.setAttribute("checked", "checked")

    【讨论】:

    • 我认为您应该查看您的答案,我在使用您的解决方案时收到AttributeError: 'WebElement' object has no attribute 'set_attribute'
    猜你喜欢
    • 2016-05-09
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2020-11-18
    • 2013-11-23
    • 2020-11-05
    相关资源
    最近更新 更多