317 lines
10 KiB
TypeScript
317 lines
10 KiB
TypeScript
import { chromium, type Browser, type Page } from 'playwright';
|
||||
|
|
import type { MetalPrice, SilverPriceData } from '../types/index.js';
|
|||
|
|
|
|||
|
|
const TARGET_URL = 'https://i.jzj9999.com/quoteh5/';
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 爬虫服务 - 获取贵金属价格数据
|
|||
|
|
*/
|
|||
|
|
export class ScraperService {
|
|||
|
|
private browser: Browser | null = null;
|
|||
|
|
private page: Page | null = null;
|
|||
|
|
private isNavigating: boolean = false; // 导航锁
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 初始化浏览器
|
|||
|
|
*/
|
|||
|
|
async init(): Promise<void> {
|
|||
|
|
try {
|
|||
|
|
this.browser = await chromium.launch({
|
|||
|
|
headless: true,
|
|||
|
|
args: ['--no-sandbox', '--disable-setuid-sandbox']
|
|||
|
|
});
|
|||
|
|
this.page = await this.browser.newPage();
|
|||
|
|
console.log('浏览器初始化成功');
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('浏览器初始化失败:', error);
|
|||
|
|
throw error;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取页面快照并提取价格数据
|
|||
|
|
*/
|
|||
|
|
async fetchPrices(): Promise<Map<string, MetalPrice>> {
|
|||
|
|
if (!this.page) {
|
|||
|
|
throw new Error('浏览器未初始化');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
// 导航到目标页面
|
|||
|
|
await this.page.goto(TARGET_URL, { waitUntil: 'networkidle', timeout: 30000 });
|
|||
|
|
|
|||
|
|
// 获取当前时间
|
|||
|
|
const timestamp = new Date().toISOString();
|
|||
|
|
|
|||
|
|
// 使用 Playwright 的 locator API 提取价格数据
|
|||
|
|
// 页面结构:所有商品行都在 e19 下
|
|||
|
|
const priceRows = await this.page.locator('div.e19 > div.generic').all();
|
|||
|
|
|
|||
|
|
const prices = new Map<string, MetalPrice>();
|
|||
|
|
|
|||
|
|
for (const row of priceRows) {
|
|||
|
|
try {
|
|||
|
|
// 获取商品名称(第一个generic元素)
|
|||
|
|
const nameEl = row.locator('> div > div').nth(0);
|
|||
|
|
const name = await nameEl.textContent();
|
|||
|
|
const trimmedName = name?.trim();
|
|||
|
|
|
|||
|
|
if (!trimmedName) continue;
|
|||
|
|
|
|||
|
|
// 获取回购价格(第二个generic元素)
|
|||
|
|
const buyPriceEl = row.locator('> div > div').nth(1);
|
|||
|
|
const buyPriceStr = await buyPriceEl.textContent();
|
|||
|
|
const buyPrice = buyPriceStr ? parseFloat(buyPriceStr.trim().replace(/,/g, '')) : 0;
|
|||
|
|
|
|||
|
|
// 获取销售价格(第三个generic元素)
|
|||
|
|
const sellPriceEl = row.locator('> div > div').nth(2);
|
|||
|
|
const sellPriceStr = await sellPriceEl.textContent();
|
|||
|
|
const sellPrice = sellPriceStr ? parseFloat(sellPriceStr.trim().replace(/,/g, '')) : 0;
|
|||
|
|
|
|||
|
|
// 获取最高价和最低价(在第二列中)
|
|||
|
|
const highPriceEl = row.locator('> div').nth(1).locator('> div').nth(0);
|
|||
|
|
const highPriceStr = await highPriceEl.textContent();
|
|||
|
|
const high = highPriceStr ? parseFloat(highPriceStr.trim().replace(/,/g, '')) : 0;
|
|||
|
|
|
|||
|
|
const lowPriceEl = row.locator('> div').nth(1).locator('> div').nth(1);
|
|||
|
|
const lowPriceStr = await lowPriceEl.textContent();
|
|||
|
|
const low = lowPriceStr ? parseFloat(lowPriceStr.trim().replace(/,/g, '')) : 0;
|
|||
|
|
|
|||
|
|
if (trimmedName && !isNaN(buyPrice)) {
|
|||
|
|
prices.set(trimmedName, {
|
|||
|
|
name: trimmedName,
|
|||
|
|
buyPrice,
|
|||
|
|
sellPrice,
|
|||
|
|
high,
|
|||
|
|
low,
|
|||
|
|
timestamp
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
} catch (err) {
|
|||
|
|
// 跳过无法解析的行
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return prices;
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('获取价格数据失败:', error);
|
|||
|
|
throw error;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 导航到目标页面(如果尚未导航)
|
|||
|
|
*/
|
|||
|
|
private async ensurePageLoaded(): Promise<void> {
|
|||
|
|
if (!this.page) {
|
|||
|
|
throw new Error('浏览器未初始化');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 如果正在导航,等待完成
|
|||
|
|
if (this.isNavigating) {
|
|||
|
|
// 等待导航完成(最多等待5秒)
|
|||
|
|
let waitCount = 0;
|
|||
|
|
while (this.isNavigating && waitCount < 50) {
|
|||
|
|
await new Promise(resolve => setTimeout(resolve, 100));
|
|||
|
|
waitCount++;
|
|||
|
|
}
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
this.isNavigating = true;
|
|||
|
|
const currentUrl = this.page.url();
|
|||
|
|
|
|||
|
|
// 如果页面未加载或URL不匹配,则导航
|
|||
|
|
if (currentUrl === 'about:blank' || !currentUrl.includes('jzj9999.com')) {
|
|||
|
|
await this.page.goto(TARGET_URL, { waitUntil: 'networkidle', timeout: 30000 });
|
|||
|
|
} else {
|
|||
|
|
// 页面已加载,刷新数据
|
|||
|
|
await this.page.reload({ waitUntil: 'networkidle', timeout: 30000 });
|
|||
|
|
}
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('页面加载失败:', error);
|
|||
|
|
throw error;
|
|||
|
|
} finally {
|
|||
|
|
this.isNavigating = false;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取白银价格数据(美白银和伦敦银)
|
|||
|
|
*/
|
|||
|
|
async fetchSilverPrices(): Promise<SilverPriceData | null> {
|
|||
|
|
if (!this.page) {
|
|||
|
|
throw new Error('浏览器未初始化');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
// 确保页面已加载
|
|||
|
|
await this.ensurePageLoaded();
|
|||
|
|
|
|||
|
|
// 使用 JavaScript 直接提取价格数据
|
|||
|
|
const prices = await this.page.evaluate(`
|
|||
|
|
(() => {
|
|||
|
|
function getSellPrice(symbolName) {
|
|||
|
|
const xpath = "//span[contains(text(), '" + symbolName + "')]";
|
|||
|
|
const span = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
|
|||
|
|
|
|||
|
|
if (!span) return null;
|
|||
|
|
|
|||
|
|
let container = span.parentElement;
|
|||
|
|
for (let i = 0; i < 10; i++) {
|
|||
|
|
if (!container) break;
|
|||
|
|
|
|||
|
|
const allElements = container.querySelectorAll('*');
|
|||
|
|
const prices = [];
|
|||
|
|
|
|||
|
|
for (let j = 0; j < allElements.length; j++) {
|
|||
|
|
const el = allElements[j];
|
|||
|
|
const text = el.textContent ? el.textContent.trim() : '';
|
|||
|
|
if (text && /^\\d+\\.?\\d*$/.test(text.replace(/,/g, ''))) {
|
|||
|
|
const num = parseFloat(text.replace(/,/g, ''));
|
|||
|
|
if (!isNaN(num) && num > 0 && num < 100000) {
|
|||
|
|
prices.push(num);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (prices.length >= 2) {
|
|||
|
|
const uniquePrices = Array.from(new Set(prices)).sort((a, b) => a - b);
|
|||
|
|
return uniquePrices.length >= 2 ? uniquePrices[1] : uniquePrices[0];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
container = container.parentElement;
|
|||
|
|
}
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
usSilver: getSellPrice('美白银'),
|
|||
|
|
londonSilver: getSellPrice('伦敦银')
|
|||
|
|
};
|
|||
|
|
})()
|
|||
|
|
`);
|
|||
|
|
|
|||
|
|
const usSilver = (prices as any).usSilver;
|
|||
|
|
const londonSilver = (prices as any).londonSilver;
|
|||
|
|
|
|||
|
|
if (!usSilver || !londonSilver) {
|
|||
|
|
console.error('未能获取到白银价格数据');
|
|||
|
|
console.log('获取到的价格: 美白银=', usSilver, ', 伦敦银=', londonSilver);
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 计算价差
|
|||
|
|
const spread = usSilver - londonSilver;
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
usSilver,
|
|||
|
|
londonSilver,
|
|||
|
|
spread,
|
|||
|
|
timestamp: new Date().toISOString()
|
|||
|
|
};
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('获取白银价格失败:', error);
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取白银价格数据(用于基线监控)
|
|||
|
|
*/
|
|||
|
|
async fetchSilverPrice(): Promise<MetalPrice | null> {
|
|||
|
|
if (!this.page) {
|
|||
|
|
throw new Error('浏览器未初始化');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
// 确保页面已加载
|
|||
|
|
await this.ensurePageLoaded();
|
|||
|
|
|
|||
|
|
// 获取当前时间
|
|||
|
|
const timestamp = new Date().toISOString();
|
|||
|
|
|
|||
|
|
// 使用新的页面结构:div.price-table-row
|
|||
|
|
const priceRows = await this.page.locator('div.price-table-row').all();
|
|||
|
|
|
|||
|
|
for (const row of priceRows) {
|
|||
|
|
try {
|
|||
|
|
// 获取商品名称(在 span.symbol-name 中)
|
|||
|
|
const nameEl = row.locator('span.symbol-name');
|
|||
|
|
const name = await nameEl.textContent();
|
|||
|
|
const trimmedName = name?.trim().replace(/\s+/g, ''); // 移除所有空格
|
|||
|
|
|
|||
|
|
// 查找"白银"商品(注意页面上可能是"白 银")
|
|||
|
|
if (trimmedName === '白银') {
|
|||
|
|
// 获取所有价格列(在 el-col 中)
|
|||
|
|
const priceCols = await row.locator('div.el-col').all();
|
|||
|
|
|
|||
|
|
if (priceCols.length >= 4) {
|
|||
|
|
// 第2列:回购价格
|
|||
|
|
const buyPriceStr = await priceCols[1].textContent();
|
|||
|
|
const buyPrice = buyPriceStr ? parseFloat(buyPriceStr.trim().replace(/,/g, '')) : 0;
|
|||
|
|
|
|||
|
|
// 第3列:销售价格
|
|||
|
|
const sellPriceStr = await priceCols[2].textContent();
|
|||
|
|
const sellPrice = sellPriceStr ? parseFloat(sellPriceStr.trim().replace(/,/g, '')) : 0;
|
|||
|
|
|
|||
|
|
// 第4列:最高价
|
|||
|
|
const highPriceStr = await priceCols[3].textContent();
|
|||
|
|
const high = highPriceStr ? parseFloat(highPriceStr.trim().replace(/,/g, '')) : 0;
|
|||
|
|
|
|||
|
|
// 第5列:最低价(如果有)
|
|||
|
|
const low = priceCols.length >= 5 ? parseFloat((await priceCols[4].textContent())?.trim().replace(/,/g, '') || '0') : 0;
|
|||
|
|
|
|||
|
|
if (!isNaN(sellPrice) && sellPrice > 0) {
|
|||
|
|
console.log(`✅ 找到白银价格: 销售=${sellPrice}, 回购=${buyPrice}, 高=${high}, 低=${low}`);
|
|||
|
|
return {
|
|||
|
|
name: '白银',
|
|||
|
|
buyPrice,
|
|||
|
|
sellPrice,
|
|||
|
|
high,
|
|||
|
|
low,
|
|||
|
|
timestamp
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
} catch (err) {
|
|||
|
|
// 跳过无法解析的行
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
console.error('未能找到"白银"商品');
|
|||
|
|
return null;
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('获取白银价格失败:', error);
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 关闭浏览器
|
|||
|
|
*/
|
|||
|
|
async close(): Promise<void> {
|
|||
|
|
if (this.browser) {
|
|||
|
|
await this.browser.close();
|
|||
|
|
this.browser = null;
|
|||
|
|
this.page = null;
|
|||
|
|
console.log('浏览器已关闭');
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取所有贵金属价格(用于调试)
|
|||
|
|
*/
|
|||
|
|
async debugFetchAllPrices(): Promise<void> {
|
|||
|
|
const prices = await this.fetchPrices();
|
|||
|
|
console.log('\n========== 所有贵金属价格 ==========');
|
|||
|
|
for (const [name, price] of prices.entries()) {
|
|||
|
|
console.log(`${name}: 回购=${price.buyPrice}, 销售=${price.sellPrice}, 高=${price.high}, 低=${price.low}`);
|
|||
|
|
}
|
|||
|
|
console.log('====================================\n');
|
|||
|
|
}
|
|||
|
|
}
|