首页 > 解决方案 > 使用 JS 设置属性值,在每个值设置后清除 Python Selenium

问题描述

给定:

                    for i in list('{}'.format(value)):
                        self.browser.execute_script(
                            "arguments[0].setAttribute('value', '{}');".format(i.replace('\n', '')),
                            self.browser.find_element_by_xpath("{}".format(xpath)))

假设要键入的给定字符串是“asd”,然后键入“a”,将其删除并键入“s”,然后删除“s”并键入“d”,并在执行另一个操作时删除(键入另一个字段或单击另一个元素)

示例 HTML 元素:

<input type="text" class="validate-input input-error" placeholder="Introdu TOKEN" value="">

PS。即使不使用 for 循环并且将值直接传递给 js 脚本,也会执行相同的清除操作。

编辑:元素选择器必须由 xpath 提供。

标签: javascriptpythonjqueryseleniumselenium-webdriver

解决方案


这是在 JS
PS 中使用 XPath 设置值的一种经过测试的解决方案:我正在使用 webdriver_manager 来管理浏览器

def setValueByXpath(xpahtValue, inputValue):
    string = "document.evaluate('" + xpahtValue + "', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value = '" + inputValue + "'"
    driver.execute_script(string)

if __name__ == '__main__':
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.get('https://www.google.com')

// call the above method with desierd xpath and value for it
    setValueByXpath('//*[@name="q"]', 'Paint Drying')

//I'm doing a search by pressing the enter button
    driver.find_element_by_xpath('//*[@name="q"]').send_keys(Keys.RETURN) 
    time.sleep(5)

    driver.quit()

推荐阅读