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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
| const express = require('express'); const bodyParser = require('body-parser'); const { chromium } = require('playwright');
const app = express(); const PORT = process.env.PORT || 3000;
app.use(bodyParser.json({ limit: '100mb' })); app.use(bodyParser.urlencoded({ limit: '100mb', extended: true }));
let browser;
async function initializeBrowser() { try { browser = await chromium.launch({ headless: true, args: [ '--no-sandbox', ] }); console.log('playwright browser initialized successfully'); } catch (error) { console.error('Failed to initialize playwright browser:', error); throw error; } }
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
function convertCookiesToDict(cookies) { const cookieDict = {}; if (Array.isArray(cookies)) { cookies.forEach(cookie => { if (cookie.name && cookie.value !== undefined) { cookieDict[cookie.name] = cookie.value; } }); } return cookieDict; } app.post('/get-cookies', async (req, res) => { const { url, html, user_agent } = req.body; if (!url || !html) { return res.status(400).json({ error: '请同时提供url和html参数' }); } let page; try { const pageOptions = {}; if (user_agent) { pageOptions.userAgent = user_agent; console.log(`使用自定义User-Agent: ${user_agent}`); } page = await browser.newPage(pageOptions); await page.route('**/*', async (route, request) => { const requestUrl = request.url(); if (requestUrl == url) { await route.fulfill({ status: 200, content_type: 'text/html', body: html }); console.log(`已处理目标URL请求: ${requestUrl}`); } else { await route.abort('aborted'); console.log(`已终止非目标URL请求: ${requestUrl}`); } }); await page.goto(url, { timeout: 30000 }); let cookies = await page.context().cookies(); cookies = convertCookiesToDict(cookies); res.json({ success: true, cookies: cookies, }); } catch (error) { console.error('处理请求时出错:', error); res.status(500).json({ success: false, error: error.message }); } finally { if (page) { await page.close(); } } });
async function startServer() { try { await initializeBrowser(); app.listen(PORT, () => { console.log(`JavaScript execution service running on port ${PORT}`); console.log(`API endpoints:`); console.log(`- POST /get-cookies: Execute JavaScript code`); }); } catch (error) { console.error('Failed to start server:', error); process.exit(1); } }
process.on('SIGINT', async () => { console.log('Shutting down...'); if (browser) { await browser.close(); } process.exit(0); });
startServer();
|