如何修复cheerio中出现的'Error: unmatched pseudo-class :flex'报错
Cheerio 选择器报
unmatched pseudo-class :flex 解决方案 报错原因
该报错并非指向 :flex 伪类不存在,而是你选择器中使用的 Tailwind 响应式类 md:flex、md:gap-2 里的冒号未被正确转义:Cheerio 依赖的 css-select 解析器会将未转义的冒号识别为伪类前缀,因此会尝试匹配不存在的 :flex、:gap-2 伪类,最终抛出错误。
可行解决方案
方案1:正确转义选择器中的冒号
JavaScript 字符串中反斜杠本身需要转义,因此原来写的 md\:flex 实际传递到 Cheerio 时仍为 md:flex,需改为双反斜杠转义:
const $ = cheerio.load(data) const name = $('#__next > div.w-full.py-10.flex.flex-col.items-center.space-y-3 > div:nth-child(1) > div.flex.hidden.md\\:flex.w-full.items-center.gap-5.md\\:gap-2 > div.flex.w-64.items-center.gap-3 > h2')
方案2:用属性选择器规避转义
如果不想处理转义逻辑,可以用 class 属性模糊匹配的方式写带冒号的类:
const $ = cheerio.load(data) const name = $('#__next > div.w-full.py-10.flex.flex-col.items-center.space-y-3 > div:nth-child(1) > div.flex.hidden[class*="md:flex"].w-full.items-center.gap-5[class*="md:gap-2"] > div.flex.w-64.items-center.gap-3 > h2')
方案3:拆分选择器用方法过滤(可读性最高)
将长选择器拆分为多步操作,用 hasClass 方法校验类名,完全规避选择器解析问题:
const $ = cheerio.load(data) // 逐层定位元素 const nextRoot = $('#__next') const level1Div = nextRoot.children('div.w-full.py-10.flex.flex-col.items-center.space-y-3').children().first() const level2Div = level1Div.children('div').filter((_, el) => { const $el = $(el) return $el.hasClass('flex') && $el.hasClass('hidden') && $el.hasClass('md:flex') && $el.hasClass('w-full') && $el.hasClass('gap-5') && $el.hasClass('md:gap-2') }) const name = level2Div.children('div.flex.w-64.items-center.gap-3').children('h2')
内容的提问来源于stack exchange,提问作者0..0
相关产品推荐
相关产品推荐

