如何用JS在Chrome控制台循环抓取HTML列表房产交易数据并解决分页问题
Chrome控制台房产数据抓取实现方案
1. 原生JS单页循环抓取实现
先获取当前页所有房产卡片节点,再通过for循环遍历提取对应字段即可,代码如下:
// 初始化存储数组 const property = []; // 获取当前页所有房产内容节点 const propertyList = document.querySelectorAll("#closed-deals-container .uc-listingCard-content"); // 循环遍历每个房产节点 for(let i = 0; i < propertyList.length; i++) { const item = propertyList[i]; property.push({ 'Name': item.querySelector('.uc-listingCard-titles > a')?.innerText?.trim() || '', 'City-State-Zip': item.querySelector('.uc-listingCard-titles > h2')?.innerText?.trim() || '', 'Price': item.querySelector('.uc-listingCard--priceGrid-sm > div')?.innerText?.trim() || '', 'Beds': item.querySelector('.uc-listingCard-subStat--beds')?.innerText?.trim() || '', 'Baths': item.querySelector('.uc-listingCard-subStat--baths')?.innerText?.trim() || '' }) } // 输出当前页抓取结果 console.log(property);
注:代码中加入了可选链操作符和空值兜底逻辑,避免某条数据缺少对应字段时报错中断执行。
2. 分页全量数据抓取实现
针对分页场景,可以通过「单页抓取→自动翻页→等待加载→循环抓取」的逻辑实现全量数据获取,基于你已有的jQuery版本扩展代码如下:
// 全局存储所有数据的数组 const allPropertyList = []; // 总页数,可根据实际分页数量修改 const totalPage = 14; // 当前抓取页数标记 let currentPage = 1; // 单页数据抓取函数 function getCurrentPageData() { const pageList = []; jQuery('div.uc-listingCard-content').each(function () { const $this = jQuery(this); pageList.push({ 'Name': $this.find('.uc-listingCard-titles > a').text().trim(), 'City-State-Zip': $this.find('.uc-listingCard-titles > h2').text().trim(), 'Price': $this.find('.uc-listingCard--priceGrid-sm > div').text().trim(), 'Beds': $this.find('.uc-listingCard-subStat--beds').text().trim(), 'Baths': $this.find('.uc-listingCard-subStat--baths').text().trim(), }); }); allPropertyList.push(...pageList); console.log(`第${currentPage}页抓取完成,累计已抓取${allPropertyList.length}条数据`); } // 翻页函数 function goToNextPage() { currentPage++; if(currentPage > totalPage) { // 所有页抓取完成,输出全量数据并自动下载为JSON文件 console.log('所有页抓取完成,全量数据如下:'); console.log(allPropertyList); const blob = new Blob([JSON.stringify(allPropertyList, null, 2)], {type: 'application/json'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = '房产交易数据.json'; a.click(); URL.revokeObjectURL(url); return; } // 替换为你页面内「下一页」按钮的真实CSS选择器,可在元素面板右键下一页按钮复制选择器 jQuery('.pagination-next').click(); // 页面加载等待时间,单位毫秒,可根据页面加载速度调整 setTimeout(() => { getCurrentPageData(); goToNextPage(); }, 2000) } // 启动抓取任务 getCurrentPageData(); goToNextPage();
注意事项:
- 若页面加载速度较慢,可适当调大2000毫秒的延迟参数,避免页面未加载完成就抓取导致数据缺失
- 部分站点有反爬限制,短时间频繁翻页可能触发风控,可进一步调大延迟降低抓取频率
内容的提问来源于stack exchange,提问作者user196286
相关产品推荐
相关产品推荐

