如何用JavaScript版Selenium点击日历中的指定年份
解决Selenium中React日期选择器年份下拉菜单的定位问题
问题描述
我尝试用JavaScript编写Selenium自动化测试,但无法填充日历日期,该日历采用下拉菜单形式。以下是我的代码片段:
const {Builder, By, Key} = require('selenium-webdriver') const test2 = async () => { let driver = await new Builder().forBrowser('chrome').build() await driver.manage().window().maximize() await driver.get('https://demoqa.com/automation-practice-form') let calendar = driver.findElement(By.xpath("//input[@id='dateOfBirthInput']")) await calendar.click() let month = driver.findElement(By.xpath("//select[@class='react-datepicker__month-select']")) await month.click() await month.sendKeys(Key.DOWN, Key.DOWN, Key.RETURN) let year = driver.findElement(By.xpath("//select[contains(@class,'react-datepicker__year-select')]")).value = "1988" }我能通过控制台输出年份1988,但无法在浏览器中选中它。除了连续按35次Key.DOWN外,还有其他方法吗?且我不能使用JavaScript的Select类。
可行解决方案
1. 直接输入目标年份
年份下拉框支持直接输入选项值,点击下拉框后直接输入目标年份再回车即可:
const yearSelect = await driver.findElement(By.xpath("//select[contains(@class,'react-datepicker__year-select')]")); await yearSelect.click(); await yearSelect.sendKeys("1988", Key.RETURN);
2. 用JavaScript直接设置元素值并触发事件
通过Selenium的executeScript操作DOM,直接设置select的value,同时触发change事件确保页面感知到选择变化:
const yearSelect = await driver.findElement(By.xpath("//select[contains(@class,'react-datepicker__year-select')]")); await driver.executeScript("arguments[0].value = '1988'; arguments[0].dispatchEvent(new Event('change'));", yearSelect);
3. 定位具体option元素点击
直接定位到值为1988的option标签,点击即可选中:
const yearOption = await driver.findElement(By.xpath("//select[contains(@class,'react-datepicker__year-select')]/option[@value='1988']")); await yearOption.click();
内容的提问来源于stack exchange,提问作者Vldmr
相关产品推荐
相关产品推荐

