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

如何用Playwright与CSS定位器获取选中元素值(如示例MMK)

获取选中元素值的CSS定位器及Playwright代码

CSS定位器

可以通过同时匹配元素的两个类来精准定位选中状态的元素:

  • 基础定位器:*.ad-search-item.ad-selected
  • 结合父元素的精准定位器:#ad-item-list .ad-search-item.ad-selected

说明:.ad-search-item.ad-selected表示同时拥有ad-search-item和ad-selected类的元素,加上父元素#ad-item-list可避免页面中其他同类元素干扰。

Playwright代码示例

JavaScript/TypeScript版本

const { test, expect } = require('@playwright/test');

test('获取选中的元素值', async ({ page }) => {
  // 导航到目标页面
  await page.goto('目标页面URL');
  
  // 定位选中元素并获取文本内容
  const selectedValue = await page.locator('#ad-item-list .ad-search-item.ad-selected').textContent();
  
  // 输出结果或做断言验证
  console.log('选中的值是:', selectedValue.trim());
  await expect(selectedValue.trim()).toBe('MMK');
});

Python版本

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("目标页面URL")
    
    # 定位选中元素并获取文本
    selected_value = page.locator("#ad-item-list .ad-search-item.ad-selected").text_content().strip()
    
    print(f"选中的值是: {selected_value}")
    assert selected_value == "MMK"
    
    browser.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 20:43:13