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

为何使用Locator筛选时filter()方法无法正常工作?

问题:Playwright中基于Locator缩小范围后filter()方法失效

我无法提供原代码,但编写了可复现该场景的HTML文件。使用VS Code的Live Server扩展运行以下测试代码时,遇到了filter()方法无法正常工作的问题:

test('test-sidebar', async ({ page }) => {
    await page.goto("http://127.0.0.1:5500/index.html")
    const site = new Site(page)
    await site.sidebar.clickLevOneItem("Lev1 item - 1")
})

搭配以下类实现时,filter()无法正常定位元素:

class Site {
    private readonly page: Page
    public readonly sidebar: SideBar

    constructor(page: Page) {
        this.page = page
        this.sidebar = new SideBar(this.page.locator(".sidebar"))
    }
}

class SideBar {
    public readonly baseNode: Locator

    constructor(baseNode: Locator) {
        this.baseNode = baseNode;
    }

    public async clickLevOneItem(name: string) {
        await this.baseNode.locator(".side-item_lev1")
            .filter({ has: this.baseNode.locator(".lev1-header", { hasText: name }) })
            .click()
    }
}

但如果将整个Page实例传入SideBar类,filter()就能正常找到DOM元素并执行点击操作:

class Site {
    private readonly page: Page
    public readonly sidebar: SideBar

    constructor(page: Page) {
        this.page = page
        this.sidebar = new SideBar(page)
    }
}

class SideBar {
    public readonly baseNode: Page

    /**
     * Create the common page object
     * @param {Locator} baseNode - 
     */
    constructor(baseNode: Page) {
        this.baseNode = baseNode;
    }

     ...
}

我不理解:为什么通过Locator缩小范围后,filter()就停止工作了?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 22:29:56