feat: 新增中广核电子商务平台爬虫
- 新增 CgnpcCrawler 爬虫类,支持中广核电子商务平台招标信息抓取 - 目标平台:https://ecp.cgnpc.com.cn,专注于核电行业采购招标 - 使用正则表达式提取招标公告,支持标题、URL和发布日期解析 - 添加完整的人类行为模拟功能(鼠标移动、滚动)降低检测风险 - 支持分页抓取,最多抓取5页数据,使用中广核特有的 btn-prev 按钮翻页 - 添加完整的单元测试文件,确保爬虫功能正常 - 统一的错误处理机制,单个爬虫失败不影响整体任务执行
This commit is contained in:
@@ -8,6 +8,7 @@ import { SzecpCrawler } from './szecp_target';
|
|||||||
import { CdtCrawler } from './cdt_target';
|
import { CdtCrawler } from './cdt_target';
|
||||||
import { EpsCrawler } from './eps_target';
|
import { EpsCrawler } from './eps_target';
|
||||||
import { CnncecpCrawler } from './cnncecp_target';
|
import { CnncecpCrawler } from './cnncecp_target';
|
||||||
|
import { CgnpcCrawler } from './cgnpc_target';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BidCrawlerService {
|
export class BidCrawlerService {
|
||||||
@@ -51,7 +52,7 @@ export class BidCrawlerService {
|
|||||||
args,
|
args,
|
||||||
});
|
});
|
||||||
|
|
||||||
const crawlers = [ChdtpCrawler, ChngCrawler, SzecpCrawler, CdtCrawler, EpsCrawler, CnncecpCrawler];
|
const crawlers = [ChdtpCrawler, ChngCrawler, SzecpCrawler, CdtCrawler, EpsCrawler, CnncecpCrawler, CgnpcCrawler];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (const crawler of crawlers) {
|
for (const crawler of crawlers) {
|
||||||
|
|||||||
51
src/crawler/services/cgnpc_target.spec.ts
Normal file
51
src/crawler/services/cgnpc_target.spec.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { CgnpcCrawler } from './cgnpc_target';
|
||||||
|
import * as puppeteer from 'puppeteer';
|
||||||
|
|
||||||
|
// Increase timeout to 60 seconds for network operations
|
||||||
|
jest.setTimeout(60000*5);
|
||||||
|
|
||||||
|
describe('CgnpcCrawler Real Site Test', () => {
|
||||||
|
let browser: puppeteer.Browser;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
browser = await puppeteer.launch({
|
||||||
|
headless: false, // Change to false to see browser UI
|
||||||
|
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (browser) {
|
||||||
|
await browser.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should visit website and list all found bid information', async () => {
|
||||||
|
console.log(`\nStarting crawl for: ${CgnpcCrawler.name}`);
|
||||||
|
console.log(`Target URL: ${CgnpcCrawler.url}`);
|
||||||
|
|
||||||
|
const results = await CgnpcCrawler.crawl(browser);
|
||||||
|
|
||||||
|
console.log(`\nSuccessfully found ${results.length} items:\n`);
|
||||||
|
console.log('----------------------------------------');
|
||||||
|
results.forEach((item, index) => {
|
||||||
|
console.log(`${index + 1}. [${item.publishDate.toLocaleDateString()}] ${item.title}`);
|
||||||
|
console.log(` Link: ${item.url}`);
|
||||||
|
console.log('----------------------------------------');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Basic assertions to ensure crawler is working
|
||||||
|
expect(results).toBeDefined();
|
||||||
|
expect(Array.isArray(results)).toBeTruthy();
|
||||||
|
// Warn but don't fail if site returns 0 items (could be empty or changed structure)
|
||||||
|
if (results.length === 0) {
|
||||||
|
console.warn('Warning: No items found. Check if website structure has changed or if list is currently empty.');
|
||||||
|
} else {
|
||||||
|
// Check data integrity of first item
|
||||||
|
const firstItem = results[0];
|
||||||
|
expect(firstItem.title).toBeTruthy();
|
||||||
|
expect(firstItem.url).toMatch(/^https?:\/\//);
|
||||||
|
expect(firstItem.publishDate).toBeInstanceOf(Date);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
203
src/crawler/services/cgnpc_target.ts
Normal file
203
src/crawler/services/cgnpc_target.ts
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
import * as puppeteer from 'puppeteer';
|
||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
|
||||||
|
// 模拟人类鼠标移动
|
||||||
|
async function simulateHumanMouseMovement(page: puppeteer.Page) {
|
||||||
|
const viewport = page.viewport();
|
||||||
|
if (!viewport) return;
|
||||||
|
|
||||||
|
const movements = 5 + Math.floor(Math.random() * 5); // 5-10次随机移动
|
||||||
|
|
||||||
|
for (let i = 0; i < movements; i++) {
|
||||||
|
const x = Math.floor(Math.random() * viewport.width);
|
||||||
|
const y = Math.floor(Math.random() * viewport.height);
|
||||||
|
|
||||||
|
await page.mouse.move(x, y, {
|
||||||
|
steps: 10 + Math.floor(Math.random() * 20) // 10-30步,使移动更平滑
|
||||||
|
});
|
||||||
|
|
||||||
|
// 随机停顿 100-500ms
|
||||||
|
await new Promise(r => setTimeout(r, 100 + Math.random() * 400));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 模拟人类滚动
|
||||||
|
async function simulateHumanScrolling(page: puppeteer.Page) {
|
||||||
|
const scrollCount = 3 + Math.floor(Math.random() * 5); // 3-7次滚动
|
||||||
|
|
||||||
|
for (let i = 0; i < scrollCount; i++) {
|
||||||
|
const scrollDistance = 100 + Math.floor(Math.random() * 400); // 100-500px
|
||||||
|
|
||||||
|
await page.evaluate((distance) => {
|
||||||
|
window.scrollBy({
|
||||||
|
top: distance,
|
||||||
|
behavior: 'smooth'
|
||||||
|
});
|
||||||
|
}, scrollDistance);
|
||||||
|
|
||||||
|
// 随机停顿 500-1500ms
|
||||||
|
await new Promise(r => setTimeout(r, 500 + Math.random() * 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 滚动回顶部
|
||||||
|
await page.evaluate(() => {
|
||||||
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
|
});
|
||||||
|
await new Promise(r => setTimeout(r, 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CgnpcResult {
|
||||||
|
title: string;
|
||||||
|
publishDate: Date;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CgnpcCrawler = {
|
||||||
|
name: '中广核电子商务平台',
|
||||||
|
url: 'https://ecp.cgnpc.com.cn/zbgg.html',
|
||||||
|
baseUrl: 'https://ecp.cgnpc.com.cn',
|
||||||
|
|
||||||
|
async crawl(browser: puppeteer.Browser): Promise<CgnpcResult[]> {
|
||||||
|
const logger = new Logger('CgnpcCrawler');
|
||||||
|
const page = await browser.newPage();
|
||||||
|
|
||||||
|
const username = process.env.PROXY_USERNAME;
|
||||||
|
const password = process.env.PROXY_PASSWORD;
|
||||||
|
if (username && password) {
|
||||||
|
await page.authenticate({ username, password });
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.evaluateOnNewDocument(() => {
|
||||||
|
Object.defineProperty(navigator, 'webdriver', { get: () => false });
|
||||||
|
Object.defineProperty(navigator, 'language', { get: () => "zh-CN"});
|
||||||
|
Object.defineProperty(navigator, 'plugins', { get: () => [1,2,3,4,5]});
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36');
|
||||||
|
await page.setViewport({ width: 1920, height: 1080 });
|
||||||
|
|
||||||
|
const allResults: CgnpcResult[] = [];
|
||||||
|
let currentPage = 1;
|
||||||
|
const maxPages = 5;
|
||||||
|
|
||||||
|
try {
|
||||||
|
logger.log(`Navigating to ${this.url}...`);
|
||||||
|
await page.goto(this.url, { waitUntil: 'networkidle2', timeout: 60000 });
|
||||||
|
|
||||||
|
// 模拟人类行为
|
||||||
|
logger.log('Simulating human mouse movements...');
|
||||||
|
await simulateHumanMouseMovement(page);
|
||||||
|
|
||||||
|
logger.log('Simulating human scrolling...');
|
||||||
|
await simulateHumanScrolling(page);
|
||||||
|
|
||||||
|
while (currentPage <= maxPages) {
|
||||||
|
logger.log(`Processing page ${currentPage}...`);
|
||||||
|
|
||||||
|
const content = await page.content();
|
||||||
|
const pageResults = this.extract(content);
|
||||||
|
|
||||||
|
if (pageResults.length === 0) {
|
||||||
|
logger.warn(`No results found on page ${currentPage}, stopping.`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
allResults.push(...pageResults);
|
||||||
|
logger.log(`Extracted ${pageResults.length} items from page ${currentPage}`);
|
||||||
|
|
||||||
|
// 模拟人类行为 - 翻页前
|
||||||
|
logger.log('Simulating human mouse movements before pagination...');
|
||||||
|
await simulateHumanMouseMovement(page);
|
||||||
|
|
||||||
|
logger.log('Simulating human scrolling before pagination...');
|
||||||
|
await simulateHumanScrolling(page);
|
||||||
|
|
||||||
|
// 查找下一页按钮 - 中广核网站分页结构
|
||||||
|
// 分页结构: <button type="button" class="btn-prev" onclick="setPageIndex(2)"><i class="fa fa-angle-right"></i></button>
|
||||||
|
const nextButtonSelector = 'button.btn-prev:not([disabled])';
|
||||||
|
const nextButton = await page.$(nextButtonSelector);
|
||||||
|
|
||||||
|
if (!nextButton) {
|
||||||
|
logger.log('Next page button not found. Reached end of list.');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.log(`Navigating to page ${currentPage + 1}...`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 点击下一页按钮
|
||||||
|
await nextButton.click();
|
||||||
|
await new Promise(r => setTimeout(r, 3000)); // 等待页面加载
|
||||||
|
} catch (navError) {
|
||||||
|
logger.error(`Navigation to page ${currentPage + 1} failed: ${navError.message}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentPage++;
|
||||||
|
|
||||||
|
// 模拟人类行为 - 翻页后
|
||||||
|
logger.log('Simulating human mouse movements after pagination...');
|
||||||
|
await simulateHumanMouseMovement(page);
|
||||||
|
|
||||||
|
logger.log('Simulating human scrolling after pagination...');
|
||||||
|
await simulateHumanScrolling(page);
|
||||||
|
|
||||||
|
// Random delay between pages
|
||||||
|
const delay = Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000;
|
||||||
|
await new Promise(resolve => setTimeout(resolve, delay));
|
||||||
|
}
|
||||||
|
|
||||||
|
return allResults;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`Failed to crawl ${this.name}: ${error.message}`);
|
||||||
|
return allResults;
|
||||||
|
} finally {
|
||||||
|
await page.close();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
extract(html: string): CgnpcResult[] {
|
||||||
|
const results: CgnpcResult[] = [];
|
||||||
|
/**
|
||||||
|
* Regex groups for ecp.cgnpc.com.cn:
|
||||||
|
* 1: URL (href属性)
|
||||||
|
* 2: Title (title属性)
|
||||||
|
* 3: Date (发布时间,格式:2026-01-23 17:00)
|
||||||
|
*
|
||||||
|
* HTML结构示例:
|
||||||
|
* <div class="zbnr">
|
||||||
|
* <div class="zbnr_left" style="width: calc(100% - 290px);">
|
||||||
|
* <a title="中广核新能源新疆公司2026年-2028年各场站线路运维检修服务框架协议"
|
||||||
|
* href="https://ecp.cgnpc.com.cn/Details.html?dataId=xxx&detailId=xxx" target="_blank">
|
||||||
|
* <h2><i>中广核新能源新疆公司2026年-2028年各场站线路运维检修服务框架协议</i></h2>
|
||||||
|
* </a>
|
||||||
|
* </div>
|
||||||
|
* <div class="zbnr_right" style="width: 270px;">
|
||||||
|
* <dl>
|
||||||
|
* <dt><p>文件获取截止时间</p><h2>2026-01-23 17:00</h2></dt>
|
||||||
|
* <dt><p>投标截止时间</p><h2>2026-01-30 09:00</h2></dt>
|
||||||
|
* </dl>
|
||||||
|
* </div>
|
||||||
|
* </div>
|
||||||
|
*/
|
||||||
|
const regex = /<div class="zbnr">[\s\S]*?<a[^>]*title="([^"]*)"[^>]*href="([^"]*)"[^>]*>[\s\S]*?<dt>[\s\S]*?<p>文件获取截止时间<\/p>[\s\S]*?<h2>\s*(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2})\s*<\/h2>[\s\S]*?<\/div>/gs;
|
||||||
|
|
||||||
|
let match;
|
||||||
|
while ((match = regex.exec(html)) !== null) {
|
||||||
|
const title = match[1]?.trim();
|
||||||
|
const url = match[2]?.trim();
|
||||||
|
const dateStr = match[3]?.trim();
|
||||||
|
|
||||||
|
if (title && url) {
|
||||||
|
results.push({
|
||||||
|
title,
|
||||||
|
publishDate: dateStr ? new Date(dateStr) : new Date(),
|
||||||
|
url: url.startsWith('http') ? url : this.baseUrl + url
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user