简体   繁体   English

无法将 JavaScript 发送到<input type="date">日历

[英]Trouble sending JavaScript into <input type="date"> calendar

Goal: Attempting to automate a calendar on Chrome using Selenium(Python + behave).目标:尝试使用 Selenium(Python + 行为)在 Chrome 上自动化日历。

The issue: The date is only being set when actually clicked through the calendar.问题:仅在实际单击日历时才设置日期。 Passing a value via JavaScript is not working.通过 JavaScript 传递值不起作用。

Note: According to docs the inputs should allow users to send input in with keys by default but that doesn't even work.注意:根据文档,默认情况下输入应该允许用户使用键发送输入,但这甚至不起作用。 It does not accept keyboard input at all.它根本不接受键盘输入。


Problem Walkthrough问题演练

  • This is the original input fields.这是原始输入字段。 The div class they are contained in is inside a #shadow-root (open):它们包含的 div 类位于 #shadow-root (打开)内:

在此处输入图像描述

  • Ignoring the Python.忽略 Python。 I will try and change the values with some simple JavaScript in the Chrome Dev Tools console:我将尝试在 Chrome 开发工具控制台中使用一些简单的 JavaScript 更改这些值:
    x = document.querySelector("#class > something").shadowRoot.querySelector("div > div > input[type=date]:nth-child(5)") #Select input for From Date
    x = "2022-05-12"
    y = document.querySelector("#class > something").shadowRoot.querySelector("div > div > input[type=date]:nth-child(5)") #Select input for To Date
    y = "2022-06-12"
  • After sending in the new values and clicking search.发送新值并单击搜索后。 It does not recognize the values as being entered:它无法识别输入的值:

在此处输入图像描述

  • However, when manually selected through the calendar:但是,当通过日历手动选择时:

在此处输入图像描述

  • The dates are accepted and as inputs:日期被接受并作为输入:

在此处输入图像描述


The HTML for the calendar is:日历的 HTML 是:

<input type="date" min="2022-01-01" max="2022-07-19">

Clearly.清楚地。 The JavaScript alone does not seem to be enough.仅 JavaScript 似乎还不够。 If you use the same method above on this calendar it will work.如果您在此日历上使用上述相同的方法,它将起作用。 However, on the calendar I am attempting this JS method will not work for some reason.但是,在日历上,我正在尝试这种 JS 方法由于某种原因不起作用。 Also, I cannot get Selenium to click and open the calendar on its own for some odd reason.此外,出于某种奇怪的原因,我无法让 Selenium 自行单击并打开日历。

Solution: Manually trigger the event ( Source )解决方案:手动触发事件( Source

let element = document.getElementById(id);
element.dispatchEvent(new Event("change")); // or whatever the event type might be

dispatchEvent() Documentatio dispatchEvent() 文档

Event() Documentation事件()文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM