如何使用JavaScript获取外部网站特定文本?爬取刷题平台解题数遇阻
如何在外部环境爬取LeetCode已解决题目数量
问题描述
我希望使用JavaScript爬取所有编程平台上我已解决的题目数量,计划的实现方式是访问每个平台的个人主页URL,获取页面上显示的解题数。针对LeetCode平台,我已找到对应的类名,并且在控制台中验证以下代码可正常获取数据,但目前不清楚如何在外部网站中使用
document.getElementByClassName方法。var url='https://leetcode.com/profileID/'; var elements = document.getElementsByClassName("text-[24px] font-medium text-label-1 dark:text-dark-label-1")[0].innerText; console.log(elements);
核心原因
浏览器的同源策略会阻止脚本跨域访问其他网站的DOM,你在控制台能运行代码是因为控制台属于LeetCode页面的上下文,不受跨域限制;但自己的外部网站脚本无法直接访问其他域的页面DOM。
可行解决方案
方案1:Node.js + Cheerio(静态页面爬取)
如果LeetCode的解题数是静态渲染在HTML里的,用Cheerio解析页面内容即可:
- 安装依赖
npm install axios cheerio - 编写爬取代码
const axios = require('axios'); const cheerio = require('cheerio'); async function getLeetCodeSolvedCount(username) { try { const url = `https://leetcode.com/${username}/`; const response = await axios.get(url); const $ = cheerio.load(response.data); // 转换类选择器适配Cheerio语法 const solvedCount = $('.text-[24px].font-medium.text-label-1.dark\\:text-dark-label-1').first().text().trim(); console.log(`LeetCode已解决题目数:${solvedCount}`); return solvedCount; } catch (error) { console.error('爬取失败:', error.message); } } // 替换成你的LeetCode用户名 getLeetCodeSolvedCount('profileID');
方案2:Node.js + Puppeteer(动态页面爬取)
如果解题数是通过JavaScript动态渲染的,Cheerio无法获取,就用Puppeteer模拟真实浏览器环境:
- 安装依赖
npm install puppeteer - 编写爬取代码
const puppeteer = require('puppeteer'); async function getLeetCodeSolvedCount(username) { const browser = await puppeteer.launch(); const page = await browser.newPage(); try { await page.goto(`https://leetcode.com/${username}/`, { waitUntil: 'networkidle2' }); // 直接复用你在控制台验证过的代码逻辑 const solvedCount = await page.evaluate(() => { return document.getElementsByClassName("text-[24px] font-medium text-label-1 dark:text-dark-label-1")[0].innerText.trim(); }); console.log(`LeetCode已解决题目数:${solvedCount}`); return solvedCount; } catch (error) { console.error('爬取失败:', error.message); } finally { await browser.close(); } } // 替换成你的LeetCode用户名 getLeetCodeSolvedCount('profileID');
注意事项
- 不要频繁发起请求,避免被LeetCode服务器封禁IP
- LeetCode可能会更新页面样式类名,届时需要重新确认目标元素的选择器
- 部分平台需要登录才能查看个人解题数据,这种情况需在爬虫中添加登录逻辑
内容的提问来源于stack exchange,提问作者Saket Yadav
相关产品推荐
相关产品推荐

