使用Apify Web Scraper提取H2文本时数组格式异常的求助
解决Apify Web Scraper返回格式异常问题
问题说明
使用Apify Web Scraper抓取网站H2标签文本时,返回的数组格式异常,每个文本被拆分为以字母索引为键的键值对,无法正常使用。
错误代码(含jQuery)
function pageFunction() { const results = [] $('h2').map(function() { results.push($(this).text()); }); return results; } console.log(pageFunction());
目标HTML示例
<h2>Mutiny</h2> <h2>Growsumo</h2> <h2>Customer.io</h2> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
错误返回结果
[ { "0": "M", "1": "u", "2": "t", "3": "i", "4": "n", "5": "y" }, { "0": "G", "1": "r", "2": "o", "3": "w", "4": "S", "5": "u", "6": "m", "7": "o" }, { "0": "C", "1": "u", "2": "s", "3": "t", "4": "o", "5": "m", "6": "e", "7": "r", "8": ".", "9": "i", "10": "o" } ]
期望正确格式
[ { "tool": "Mutiny" }, { "tool": "Growsumo" }, { "tool":"Customer.io" } ]
解决方案
原因分析
- jQuery的
map方法返回的是jQuery对象而非原生数组,直接处理可能导致Apify解析异常; - 原代码中直接push字符串,Apify会将字符串视为类数组对象,拆分出每个字符的索引键值对。
修正代码(两种可选)
方法1:使用each循环构建对象数组
function pageFunction() { const results = []; $('h2').each(function() { // 包装为指定结构的对象,trim()去除可能的首尾空白 results.push({ tool: $(this).text().trim() }); }); return results; }
方法2:使用map+get()转原生数组
function pageFunction() { // map返回jQuery集合,调用get()转为原生数组 return $('h2').map(function() { return { tool: $(this).text().trim() }; }).get(); }
内容的提问来源于stack exchange,提问作者Baptiste Derenne
相关产品推荐
相关产品推荐

