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

Playwright Locator count返回0问题:可获取单元素文本但无法统计全部

问题分析与解决

核心错误

你第二个locator的XPath语法写错了,把span元素的class属性选择器写成了//span["copy-the-code-wrap copy-the-code-style-button copy-the-code-inside-wrap"],这不符合XPath语法规范——匹配class属性必须用[@class="属性值"]的格式,你漏掉了@class=,导致Playwright找不到任何匹配元素,所以count()返回0。

修正后的代码

把第二个locator的XPath改成正确格式即可,同时可以用Playwright内置的等待逻辑替代time.sleep,让操作更可靠:

from playwright.sync_api import sync_playwright

def main():
    with sync_playwright() as p:
        browser = p.firefox.launch(headless=False)
        page = browser.new_page()
        url = "https://www.useragentlist.net/"
        page.goto(url)
        
        # 用内置等待确保目标元素加载完成,替代time.sleep
        target_locator = page.locator('xpath=//span[@class="copy-the-code-wrap copy-the-code-style-button copy-the-code-inside-wrap"]/pre/code/strong')
        target_locator.wait_for()

        # 获取单个元素文本(取第一个匹配项)
        test = target_locator.first.inner_text()
        print(test)

        # 统计所有匹配元素的数量
        count = target_locator.count()
        print(count)

        # 遍历获取所有元素的文本
        all_texts = target_locator.all_inner_texts()
        for text in all_texts:
            print(text)

        browser.close()

if __name__ == '__main__':
    main()

额外说明

  1. 第一个locator里的[1]是强制取第一个匹配元素,所以能成功获取文本,但统计所有元素时不需要加这个限定。
  2. 用locator.wait_for()替代time.sleep,可以根据元素实际加载状态触发后续操作,避免因网络波动导致的元素未加载问题。
  3. 直接调用all_inner_texts()方法就能一次性获取所有匹配元素的文本,无需手动逐个遍历。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:43:09