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

如何在Puppeteer中获取所有前缀匹配指定字符串的选择器

JavaScript 前缀匹配选择器实现方案

原生方案(优先推荐)

JS 调用 DOM 查询方法时,可以直接使用 CSS 自带的前缀匹配选择器语法,性能最优,无需额外逻辑:

  • 如果你要匹配的是id 前缀为 button_selector_ 的元素:
// ^= 是CSS属性前缀匹配标识符
const matchedElements = document.querySelectorAll('[id^="button_selector_"]')
  • 如果你要匹配的是类名前缀为 button_selector_ 的元素(兼容元素有多个类名的场景):
const matchedElements = Array.from(document.querySelectorAll('button')).filter(el => {
  return Array.from(el.classList).some(className => className.startsWith('button_selector_'))
})

通用通配符匹配方案

如果需要类似 grok 里 * 通配符的灵活匹配能力,可以自己实现一个通配符转正则的工具函数:

/**
 * 通配符字符串转正则表达式
 * @param {string} pattern 带*的通配符规则
 * @returns {RegExp} 转换后的正则对象
 */
function createWildcardReg(pattern) {
  // 转义正则特殊字符,再把*替换为任意字符匹配规则
  const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')
  return new RegExp(`^${escaped}$`)
}

// 使用示例
const matchRule = createWildcardReg('button_selector_*')
console.log(matchRule.test('button_selector_123')) // 输出 true
console.log(matchRule.test('button_selector_abc987')) // 输出 true
console.log(matchRule.test('other_btn_123')) // 输出 false

拓展CSS属性匹配语法

你可以根据需求直接使用原生CSS属性匹配规则,覆盖大多数简单场景:

  • [attr^="xxx"]:匹配属性值以xxx开头的元素
  • [attr$="xxx"]:匹配属性值以xxx结尾的元素
  • [attr*="xxx"]:匹配属性值任意位置包含xxx的元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:06:05