JavaScript抓取电商商品页标题价格颜色及CORS跨域问题解决
解决CORS问题并完成数据抓取的可行方案
CORS是浏览器端的同源安全限制,直接从前端跨域请求第三方站点必然会被拦截,可根据使用场景选择以下方案解决:
方案1:服务端中转请求(生产环境可用,最稳定)
服务端发起HTTP请求不存在CORS限制,你可以先搭建一个简单的后端中转接口:
- 前端先请求自己的后端接口,把要抓取的Michael Kors商品URL作为参数传递
- 后端向目标商品页发起请求拿到页面源码,再返回给前端
- 前端拿到源码后解析DOM提取对应类名的数据即可
以下是Node.js + Express的简单中转接口示例:
const express = require('express'); const axios = require('axios'); const app = express(); const port = 3000; // 允许本地前端跨域调用 app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); next(); }); app.get('/fetchMKPage', async (req, res) => { const targetUrl = decodeURIComponent(req.query.targetUrl); try { const pageRes = await axios.get(targetUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } }); res.send(pageRes.data); } catch (err) { res.status(500).send('请求失败'); } }); app.listen(port, () => console.log(`中转服务已启动,端口:${port}`));
调整后的前端抓取代码:
const targetUrl = 'https://www.michaelkors.com/mercer-gallery-medium-logo-tote-bag/_/R-US_30F1GZ5T6B?color=2170'; // 调用自己的中转接口 fetch(`http://localhost:3000/fetchMKPage?targetUrl=${encodeURIComponent(targetUrl)}`) .then(res => res.text()) .then(html => { // 解析页面提取数据 const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); const title = doc.querySelector('.product-name')?.textContent.trim(); const wasPrice = doc.querySelector('.listPrice')?.textContent.trim(); const nowPrice = doc.querySelector('.salePrice')?.textContent.trim(); // 提取所有在售颜色,可根据实际页面元素类名调整选择器 const colors = Array.from(doc.querySelectorAll('.color-swatch-item')) .map(item => item.getAttribute('data-color-name')) .filter(Boolean) .join(', '); // 输出结果 console.log({ Title: title, 'Was Price': wasPrice, 'Now Price': nowPrice, Color: colors }); }) .catch(err => console.log(err));
方案2:本地测试临时方案(仅个人调试用,无法上线)
如果只是自己本地测试抓取数据,不需要给其他用户使用,可以选以下两种更简单的方式:
- 关闭Chrome浏览器的CORS安全校验:Windows系统给Chrome快捷方式加启动参数
--disable-web-security --user-data-dir="C:\ChromeDevTemp",Mac系统终端执行open -n /Applications/Google\ Chrome.app/ --args --disable-web-security --user-data-dir=/Users/你的用户名/ChromeDevTemp,打开调整后的浏览器再运行原来的代码就不会触发CORS报错 - 用Tampermonkey(油猴)脚本运行抓取代码,油猴脚本自带跨域权限,只要在脚本头部加一行
// @grant GM_xmlhttpRequest就能直接跨域请求目标站点
注意事项
- Michael Kors站点有反爬机制,请求频率过高会被封IP,测试时建议控制请求间隔在3秒以上
- 如果页面数据是前端动态渲染的,直接爬源码可能拿不到对应元素,需要改用Puppeteer等无头浏览器工具渲染页面后再提取数据
内容的提问来源于stack exchange,提问作者Xin
相关产品推荐
相关产品推荐

