网页数据快速提取:JavaScript控制台方法

快速开始

F12 打开浏览器开发者工具 → 切换到 Console 标签 → 粘贴代码并回车


方法一:基础提取

const positions = Array.from(document.querySelectorAll('.el-select-dropdown__item span'))
    .map(span => span.textContent.trim())
    .filter(text => text.length > 0);

copy(positions.join('\n'));  // 复制到剪贴板
alert('已复制' + positions.length + '个岗位!');

代码解析:

代码 作用
document.querySelectorAll('.selector') 用CSS选择器查找所有匹配元素
Array.from() 转为数组
.map(span => span.textContent.trim()) 提取每个元素的文本并去除空格
.filter(text => text.length > 0) 过滤掉空值
.join('\n') 用换行符连接数组
copy() 复制到剪贴板(控制台专用)

方法二:带编号提取

const positions = Array.from(document.querySelectorAll('.el-select-dropdown__item span'))
    .map(span => span.textContent.trim())
    .filter(text => text.length > 0)
    .map((pos, index) => `${index + 1}. ${pos}`);  // 添加序号

copy(positions.join('\n'));

新增知识点:

  • map((pos, index) => ...) – index 是当前元素索引(从0开始)
  • 模板字符串 `${变量}` – 方便拼接变量和文本

如何自行拓展

1. 查找正确的选择器

右键目标元素 → 检查 → 在Elements面板中右键 → Copy selector

// 替换为你的选择器
document.querySelectorAll('.your-selector-here')

2. 提取多个字段

const jobs = Array.from(document.querySelectorAll('.job-item')).map(item => ({
    title: item.querySelector('.title').textContent.trim(),
    salary: item.querySelector('.salary').textContent.trim(),
    company: item.querySelector('.company').textContent.trim()
}));

console.table(jobs);  // 表格展示
copy(JSON.stringify(jobs, null, 2));  // 复制JSON

3. 常用数据处理

// 去重
const unique = [...new Set(positions)];

// 筛选关键词
const filtered = positions.filter(pos => pos.includes('技术'));

// 导出Markdown
const markdown = positions.map(p => `- ${p}`).join('\n');
copy(markdown);

核心API速查

API 作用 示例
.map() 遍历转换 arr.map(x => x * 2)
.filter() 筛选 arr.filter(x => x > 0)
.join() 数组转字符串 arr.join(', ')
textContent 获取文本 element.textContent
querySelector() 查找单个元素 item.querySelector('.title')

进阶方向

  • JavaScript基础 – 数组方法(map/filter/reduce)
  • DOM操作 – querySelector、元素属性
  • 正则表达式 – 文本匹配与提取
  • 自动化工具 – Puppeteer(自动化浏览器操作)

推荐资源: MDN Web Docs、JavaScript.info

发表回复

Your email address will not be published. Required fields are marked *.

*
*