使用Cheerio模块无法获取Roblox头像及指定元素的技术问题
Roblox网页抓取问题(Cheerio)
遇到的技术问题
- 无法获取Roblox平台用户的头像
- 尝试返回
.avatar-card-image子元素时,部分元素不可见 - 使用选择器
$('img .ng-isolate-scope').attr('src')无法获取头像链接
相关Node.js代码
const fetch = require('node-fetch') const cheerio = require('cheerio') const request = require('request') function fetchUser(username) { var user = username const api = "https://api.roblox.com/users/get-by-username?username=" let apiID = api + user return fetch(apiID) .then((response) => response.json()) .then((function(data) { var ID = null if (data['Id']) { ID = data['Id'] } else if (data['success'] === false) { ID = data['errorMessage'] } return ID })) } function getInfoUser(id) { var info = { nickname: null, username: null, avatar: null } request({method: 'GET', url: 'https://www.roblox.com/users/' + id +'/profile'}, function(err, response, body) { if (err) return console.log(err) $ = cheerio.load(body) const header = $('.header-title') const names = $('.header-names') const avatar = $('img .ng-isolate-scope') info.nickname = names.find('.profile-display-name').text().replace(/\s/g, '') info.username = header.find('.font-header-1').text().replace(/\s/g, '') info.avatar = avatar.html() console.log(info) const div = $('.avatar-headshot-lg').children('.avatar-card-link').children('.avatar-card-image').html() console.log(div) }) } fetchUser('Stephan_chan').then((result) => getInfoUser(result))
执行输出截图

解决方案
问题根源
Roblox用户头像、.avatar-card-image这类元素是通过AngularJS动态渲染的,Cheerio只能抓取静态HTML源码,无法获取JS动态生成的内容;同时你的选择器写法存在语法错误。
具体修复方案
修正选择器语法错误
你写的$('img .ng-isolate-scope')表示查找img标签下的.ng-isolate-scope子元素,正确写法应为$('img.ng-isolate-scope')(去掉空格,代表同时拥有img标签和ng-isolate-scope类的元素)。但即便修正,静态抓取仍无法拿到动态渲染的头像内容。改用Roblox官方API获取头像
直接调用Roblox头像API是最稳定可靠的方式,避免依赖页面结构变化:- 头像API地址:
https://thumbnails.roblox.com/v1/users/avatar-headshot?userIds={用户ID}&size=420x420&format=Png&isCircular=false
修改后的getInfoUser函数:
function getInfoUser(id) { var info = { nickname: null, username: null, avatar: null } // 抓取用户基本信息 request({method: 'GET', url: 'https://www.roblox.com/users/' + id +'/profile'}, function(err, response, body) { if (err) return console.log(err) $ = cheerio.load(body) const header = $('.header-title') const names = $('.header-names') info.nickname = names.find('.profile-display-name').text().replace(/\s/g, '') info.username = header.find('.font-header-1').text().replace(/\s/g, '') // 调用头像API获取头像链接 fetch(`https://thumbnails.roblox.com/v1/users/avatar-headshot?userIds=${id}&size=420x420&format=Png&isCircular=false`) .then(res => res.json()) .then(data => { if (data.data && data.data[0]) { info.avatar = data.data[0].imageUrl; } console.log(info); }) .catch(apiErr => console.log(apiErr)); }) }- 头像API地址:
解决动态元素不可见问题
网页中.avatar-card-image属于JS动态生成内容,静态HTML源码中不存在,因此Cheerio无法抓取。改用官方API彻底规避了这个问题,同时数据获取效率更高。
额外建议:request模块已被弃用,建议统一使用node-fetch或axios处理HTTP请求,减少依赖风险。
内容的提问来源于stack exchange,提问作者zenqiprolol
相关产品推荐
相关产品推荐

