Spaces:
Paused
Paused
File size: 2,888 Bytes
86b6928 dd27eb1 86b6928 dd27eb1 86b6928 b0e7c90 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 8e647b0 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 dd27eb1 86b6928 |
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 |
import { chromium } from 'playwright';
import fs from 'fs';
import config from './config.js';
import { fileURLToPath } from 'url';
import path from 'path';
import { loadCookies } from './utils/common-utils.js';
import { info, error } from './utils/logger.js';
async function login() {
info('启动浏览器...');
const browser = await chromium.launch(config.browserOptions);
const context = await browser.newContext();
const cookies = loadCookies(config.cookieFile, config.cookiesFromEnv);
await context.addCookies(cookies);
const page = await context.newPage();
try {
info(`导航到登录页面:${config.webideUrl}...`);
// 首先访问主页面,通常会重定向到登录页面
await page.goto(config.webideUrl);
// 等待页面加载
await page.waitForTimeout(config.waitTimes.pageLoad);
info('当前页面URL:', page.url());
info('页面标题:', await page.title());
// 检查是否已经登录(如果页面包含编辑器元素,说明已登录)
const isLoggedIn = await page.locator(config.selectors.editor).count() > 0;
if (isLoggedIn) {
info('检测到已经登录状态,保存cookie...');
} else {
info('需要登录,请在浏览器中手动完成登录过程...');
info('登录完成后,请按 Enter 键继续...');
// 等待用户手动登录
await waitForUserInput();
// 等待登录完成,检查是否出现编辑器界面
info('等待登录完成...');
try {
await page.goto(config.webideUrl);
await page.waitForSelector(config.selectors.editor, {
timeout: 60000
});
} catch (err) {
info('未检测到编辑器界面,但继续保存cookie...');
}
}
// 保存cookies
const cookies = await context.cookies();
fs.writeFileSync(config.cookieFile, JSON.stringify(cookies, null, 2));
info(`Cookies已保存到 ${config.cookieFile}`);
info(`保存了 ${cookies.length} 个cookies`);
// 显示保存的cookie信息(仅显示名称,不显示值)
info('保存的cookie名称:');
cookies.forEach(cookie => {
info(` - ${cookie.name} (域名: ${cookie.domain})`);
});
} catch (err) {
error('登录过程中发生错误:', err);
} finally {
await browser.close();
}
}
// 等待用户输入的辅助函数
async function waitForUserInput() {
const { default: readline } = await import('readline');
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('', () => {
rl.close();
resolve();
});
});
}
// 运行命令执行脚本
const __filename = fileURLToPath(import.meta.url);
const scriptPath = path.resolve(process.argv[1]);
if (path.resolve(__filename) === scriptPath) {
login().catch(error);
}
|