All checks were successful
Docker Build and Push / build-image (push) Successful in 3m16s
101 lines
2.9 KiB
JavaScript
101 lines
2.9 KiB
JavaScript
const axios = require('axios');
|
||
const cheerio = require('cheerio');
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const { PrismaClient } = require('../../generated/prisma');
|
||
|
||
const prisma = new PrismaClient();
|
||
|
||
// 数据源URL(需要根据实际情况修改)
|
||
const DATA_SOURCE_URL = 'https://example.com/data';
|
||
|
||
// 通用数据爬取函数
|
||
async function scrapeData() {
|
||
try {
|
||
console.log('开始爬取数据...');
|
||
|
||
// 1. 发送HTTP请求获取页面内容
|
||
const response = await axios.get(DATA_SOURCE_URL, {
|
||
headers: {
|
||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
||
}
|
||
});
|
||
|
||
// 2. 解析HTML内容
|
||
const $ = cheerio.load(response.data);
|
||
|
||
// 3. 提取数据(需要根据实际网站结构修改)
|
||
const data = [];
|
||
|
||
// 示例:从表格中提取数据
|
||
$('table').each((tableIndex, table) => {
|
||
$(table).find('tr').each((rowIndex, row) => {
|
||
if (rowIndex > 0) { // 跳过表头
|
||
const cells = $(row).find('td');
|
||
// 根据实际表格结构提取数据
|
||
// 示例:假设第一列是日期,第二列是数值
|
||
if (cells.length >= 2) {
|
||
const date = $(cells[0]).text().trim();
|
||
const value = parseFloat($(cells[1]).text().trim());
|
||
|
||
if (date && !isNaN(value)) {
|
||
data.push({
|
||
date,
|
||
value
|
||
});
|
||
}
|
||
}
|
||
}
|
||
});
|
||
});
|
||
|
||
console.log(`爬取到 ${data.length} 条数据`);
|
||
|
||
// 4. 存储数据到数据库(需要根据实际表结构修改)
|
||
for (const item of data) {
|
||
try {
|
||
// 这里需要根据实际表结构修改
|
||
// 示例:存储到某个表
|
||
/*
|
||
const existing = await prisma.someTable.findUnique({
|
||
where: { date: item.date }
|
||
});
|
||
|
||
if (existing) {
|
||
// 更新现有数据
|
||
await prisma.someTable.update({
|
||
where: { date: item.date },
|
||
data: { value: item.value }
|
||
});
|
||
console.log(`更新数据: ${item.date} - ${item.value}`);
|
||
} else {
|
||
// 创建新数据
|
||
await prisma.someTable.create({
|
||
data: item
|
||
});
|
||
console.log(`新增数据: ${item.date} - ${item.value}`);
|
||
}
|
||
*/
|
||
} catch (error) {
|
||
console.error(`处理数据时出错:`, error.message);
|
||
}
|
||
}
|
||
|
||
console.log('数据爬取和存储完成!');
|
||
|
||
} catch (error) {
|
||
console.error('爬取数据时出错:', error.message);
|
||
} finally {
|
||
// 关闭Prisma连接
|
||
await prisma.$disconnect();
|
||
}
|
||
}
|
||
|
||
// 导出函数
|
||
module.exports = { scrapeData };
|
||
|
||
// 如果直接运行此文件
|
||
if (require.main === module) {
|
||
scrapeData();
|
||
}
|