在Selenium for Python中绕过只读HTML元素?

2024-06-28 14:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一项任务正试图使用Python在selenium中实现自动化,其中包括选择日期。网站上的日期选择有一个输入框,当您选择时,它会下拉一个非常标准的日期表

输入“文本”框设置为只读,我在让Selenium查找我要求它选择的日期时遇到了一些困难,能够简单地将所需日期的_键发送到输入框将是一个更容易的实现

经过研究,我在JS中找到了这个解决方案:

((JavascriptExecutor)driver).executeScript("arguments[0].value=arguments[1]", element, "my text to put in the value");

在Python中有没有类似的函数可以实现同样的效果

我对Javascript不太熟悉,所以我的能力不允许我将其转换为Python

任何帮助都将不胜感激


Tags: 文本标准value网站driverseleniumjselement
2条回答

selenium python中存在相同的函数,可以从驱动程序对象访问该函数:

driver.execute_script("arguments[0].value=arguments[1]", element, "my text to put in the value")

你说你不懂javascript,所以给你一个简短的提纲

您正在将3个变量传递给execute_script

  • 第一个是执行arguments[0].value=arguments[1]的js。这将查找2个输入参数。它用第二个输入的值设置第一个输入的.value
  • element是您传入的下一个变量,是第一个js参数(argument[0]),是您已经识别的webelement
  • "my text...blah"是第二个参数(argument[1]),是要设置的字符串值

有关此方法和其他方法的更多信息,请参见python-selenium docs

执行脚本包括以下内容:

execute_script(script, *args) Synchronously Executes JavaScript in the current window/frame.

Args: script: The JavaScript to execute. *args: Any applicable arguments for your JavaScript. Usage: driver.execute_script(‘return document.title;’)

Selenium客户端等效的代码行为:

driver.execute_script("arguments[0].value=arguments[1]", element, "my text to put in the value")

It is to be noted the JavaScript command part remains the same and only the method name varies as per the binding art, be it Java, Python, C#, etc.

相关问题 更多 >