如何用Cheerio在JavaScript中提取div内Location对应文本?
问题:提取HTML中Location对应的文本值
目标HTML结构:
<div class="col-md-7 order-md-1"> <strong>Name: </strong> Adept Rider<br> <strong>Type: </strong> Craftable<br> <strong>Location: </strong> Summerset<br> <strong>Traits needed to craft: </strong> 3<br> <strong>Requires DLC: </strong> Summerset<br> <br><strong>Obtainable items: </strong> <ul> <li>Weapons</li> <li>Light Armor</li> <li>Jewels</li> <li>Heavy Armor</li> <li>Medium Armor</li> </ul> <br> <br> </div>
想要定义const location变量,使其输出字符串'Summerset',尝试了两种方法都没得到预期结果:
- 方法1:仅获取
<strong>的文本,只输出Location:const location = $('strong:contains("Location:")').text(); console.log(location); // 输出: Location: - 方法2:用
next()尝试获取后续内容,无输出const location = $('strong:contains("Location:")').next().text(); console.log(location); // 无输出,预期是' Summerset'
已确认HTML加载正常,因为不加next()能正确输出Location: 。
解决方案
为什么next()无效?
因为<strong>Location: </strong>后面的Summerset是文本节点,不是HTML元素节点,而jQuery的next()方法只会查找同级的元素节点,所以找不到对应内容,返回空字符串。
可行方法1:直接获取相邻文本节点
通过DOM元素的nextSibling属性获取紧邻的文本节点,再处理内容:
const locationEl = $('strong:contains("Location:")')[0]; const location = locationEl.nextSibling.textContent.trim(); console.log(location); // 输出: Summerset
可行方法2:拆分父元素文本提取
先拿到包含目标内容的整行文本,再通过字符串拆分、修剪得到结果:
const locationLine = $('strong:contains("Location:")').parent().text(); const location = locationLine.split('Location:')[1].trim(); console.log(location); // 输出: Summerset
可行方法3:用contents()筛选文本节点
利用jQuery的contents()获取所有子节点,筛选出文本节点后提取内容:
const location = $('strong:contains("Location:")') .contents() .filter(function() { return this.nodeType === 3; // 筛选类型为文本的节点 }) .text() .trim(); console.log(location); // 输出: Summerset
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

