javascript - 使用 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 提供。
解决方案
这是在 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()
推荐阅读
- python - 试图将伪代码转换为 Python 代码
- vba - 您如何在 VBA 中指定货币文字
- react-native - 如何使用 react-native 应用程序中的语言下拉菜单翻译移动应用程序文本?
- heroku - Strapi + Heroku 部署失败:npm ERR!代码 ERESOLVE
- sql - 获取第二个最大日期json对象(postgres)
- python - 如何解决错误“发生错误:Django/Python3 应用程序没有此类文件或目录”
- c++ - 为什么我需要使用队列
q 并且不能使用队列 问? - javascript - 将文件上传到 Firebase 存储时遇到问题
- php - 我有一个未序列化的数据。现在我如何剪切数组的第一部分并将其转换为 json 格式?
- python - 如何按列表中的出现频率对 Django 查询集进行排序并确保其余对象跟随?