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

如何用Playwright定位关联特定文本的指定testid的div元素

定位关联“Internal Description”的Rich Text Editor元素

要定位关联“Internal Description”的data-testid="rich-text-editor"元素,你可以使用以下几种Playwright定位方式:

方法1:利用父容器层级定位

先找到包含目标文本的元素,回到其共同父容器后,再定位内部的编辑器元素:

await page.getByText('Internal Description')
  .locator('..') // 回到包含文本和编辑器的父div
  .getByTestId('rich-text-editor');

方法2:使用XPath精准匹配

通过XPath直接筛选父容器包含指定文本的目标元素:

await page.locator('//div[div[text()="Internal Description"]]//div[@data-testid="rich-text-editor"]');

如果文本可能包含空格或换行,可改用contains进行模糊匹配:

await page.locator('//div[contains(div, "Internal Description")]//div[@data-testid="rich-text-editor"]');

方法3:通过filter筛选元素

对所有匹配rich-text-editor的元素进行过滤,只保留祖先容器包含目标文本的那个:

await page.getByTestId('rich-text-editor')
  .filter({ hasAncestor: page.locator('div:has-text("Internal Description")').locator('..') });

内容的提问来源于stack exchange,提问作者one-hand-octopus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:20:15