1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| const puppeteer = require('puppeteer-core'); const fs = require('fs'); const path = require('path');
(async () => { try { console.log('正在启动浏览器...'); const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'] });
console.log('正在创建新页面...'); const page = await browser.newPage(); await page.setViewport({ width: 1280, height: 800 });
const url = 'https://www.bilibili.com/opus/1181258307271131136'; console.log(`正在访问页面: ${url}`); await page.goto(url, { waitUntil: 'networkidle2', timeout: 60000 });
console.log('页面加载成功!正在移除指定元素...'); const elementsToRemove = [ 'header', '.right-sidebar-wrap', '.bili-tabs', '.opus-module-bottom' ];
for (const selector of elementsToRemove) { await page.evaluate((sel) => { const element = document.querySelector(sel); if (element) { console.log(`正在移除元素: ${sel}`); element.remove(); } else { console.log(`元素未找到: ${sel}`); } }, selector); }
console.log('元素移除完成!正在生成优化后的 PDF...'); const outputPath = path.join(__dirname, 'bilibili_opus_optimized_1181258307271131136.pdf'); await page.pdf({ path: outputPath, format: 'A4', printBackground: true, margin: { top: '1cm', right: '1cm', bottom: '1cm', left: '1cm' } });
console.log(`优化后的 PDF 已生成: ${outputPath}`); const title = await page.title(); console.log(`页面标题: ${title}`); await browser.close(); console.log('浏览器已关闭'); } catch (error) { console.error('错误:', error); try { const { execSync } = require('child_process'); console.log('尝试使用 wget 获取页面内容...'); execSync('wget -O bilibili_optimized_page.html https://www.bilibili.com/opus/1181258307271131136 2>&1'); console.log('页面内容已保存到 bilibili_optimized_page.html'); } catch (wgetError) { console.error('wget 也失败了:', wgetError); } } })();
|