You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤含disabled类的getByText元素以点击有效日历日期?

问题描述

日历组件中会重复显示相同日期(如上月28号和当月28号),其中禁用的日期元素带有disabled类,示例代码如下:

禁用日期的DOM结构:

<div role="gridcell" class="ngb-dp-day disabled" tabindex="-1" aria-label="Sunday, July 28, 2024">
<span _ngcontent-dug-c147="" class="custom-day weekend disabled"> 28 </span>
<!----><!---->
</div>

有效日期的DOM结构(不含disabled类):

<div role="gridcell" class="ngb-dp-day" tabindex="-1" aria-label="Wednesday, August 28, 2024">
<span _ngcontent-dug-c147="" class="custom-day"> 28 </span>
<!----><!---->
</div>

当前使用page.getByText("28", { exact: true }).click()执行点击时,因存在两个文本相同的元素而失败。尝试过以下代码但无法正常工作:

await this.page.getByText("28")
    .filter({ hasNot: this.page.locator('span[class~="disabled"]').click()

请问如何过滤掉带有disabled类的元素,正确点击有效日期?


解决方法

方法一:修正filter的使用方式

你之前的代码错误在于filter的hasNot参数不需要直接调用.click(),且定位器应指向当前元素下的子元素。正确写法如下:

await this.page.getByText("28", { exact: true })
  .filter({ hasNot: this.page.locator("span.disabled") })
  .click();

也可以直接定位到不带disabled类的日期容器,再筛选文本:

await this.page.locator("div.ngb-dp-day:not(.disabled)")
  .getByText("28", { exact: true })
  .click();

方法二:直接组合选择器定位有效元素

通过CSS选择器直接匹配不带disabled类且文本为28的元素:

// 定位容器元素
await this.page.locator('div.ngb-dp-day:not(.disabled):has-text("28")').click();

// 或定位日期文本所在的span元素
await this.page.locator('span.custom-day:not(.disabled):has-text("28")').click();

方法三:通过aria-label精准定位

如果知道目标日期的完整aria-label内容,可以直接用这个属性定位,彻底避免歧义:

await this.page.getByLabel("Wednesday, August 28, 2024").click();

内容的提问来源于stack exchange,提问作者STK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:59:51