javascript - 如何通过 Python 使用 Selenium 将日期作为文本直接发送到具有只读属性的日历控件?

标签 javascript python selenium calendar readonly-attribute

我正在尝试使用 python 和 selenium 从日历中选择一个日期,但我需要一些帮助,我是在 VBA 中完成的,但我想在 python 中完成。 提前致谢。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Firefox(executable_path=r'..\geckodriver.exe')
driver.get('https://burghquayregistrationoffice.inis.gov.ie/Website/AMSREG/AMSRegWeb.nsf/AppSelect?OpenForm')    

# this is the problem
driver.find_element_by_id('GNIBExDT').send_keys(10/08/2019)

最佳答案

这是一个只读输入 - 如果您查看 HTML src,它有 readonly 属性。这意味着 send_keys,它通过模拟按键操作来工作,就好像它是一个真实的用户(也触发任何监听输入变化的事件监听器),试图输入你的值(value),但不能,因为它是只读的。但是,您仍然可以手动设置它 - 尝试:

driver.execute_script("document.getElementById('GNIBExDT').value = '10/08/2019'")

这将执行以下 JS 代码:

document.getElementById('GNIBExDT') // Equivalent of driver.find_element_by_id('GNIBExDT') in pure JS
    .value = // Used to set the 'value' of the input, which is what will be read on the backend when the form is submitted. This just sets the value directly, so it doesn't matter if it's read-only.
    '10/08/2019' // The date, in string form.

他们似乎只是在示例网站上使用基本字符串来表示日期,因为它是一个自定义日期选择器。因此,他们没有做任何特别的事情,例如使用实际的日期格式或 Date 对象。但是,由于基于标题,这就是您想要的,我将举一个例子来为任何用谷歌搜索过这个问题的人做这样的事情:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Firefox(executable_path=r'..\geckodriver.exe')
driver.get('https://www.w3schools.com/html/tryit.asp?filename=tryhtml_input_date')

driver.execute_script("document.getElementsByTagName('input')[0]"  # Get the date picker from the DOM
                     +".valueAsDate"  # Set the value *as a date object* - this is only available in real date pickers (`<input type='date'>`)
                     +" = new Date('2020-03-11')"  # We therefore need to define it as a date object, which we do in 'yyyy-mm-dd hh:mm:ss GMT+hhmm' format
)

关于javascript - 如何通过 Python 使用 Selenium 将日期作为文本直接发送到具有只读属性的日历控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57449375/

相关文章:

python - 将列表附加到字典

selenium - Selenium Chromedriver测试在Windows docker容器中失败并带有http请求超时

ruby - Net::ReadTimeout (Net::ReadTimeout) Selenium ruby

javascript - 是否可以将 Google 的 Web Speech API 与非 Web 应用程序结合使用?

javascript - Android WebView HTML 输入按键不会触发

JavaScript:重构,避免 array.push()

javascript - 使用站点范围与本地页面脚本时可能存在 JavaScript 框架版本冲突

python - 正则表达式不返回任何结果

python - 我应该多久检查一次过度拟合?我如何自动检测/采取行动?

c# - Selenium IE WebDriver : NoSuchElementException