Files
nanocode/playwright-hotspots/scripts/weibo_post_with_cookie.js
T
Ubuntu 32b43f85bd a
2026-07-03 16:58:28 +08:00

144 lines
4.6 KiB
JavaScript

/**
* 使用 Cookie 登录微博并发送测试微博
*/
const puppeteer = require('puppeteer-core');
const { getLaunchOptions } = require('../config/browser');
const fs = require('fs');
const COOKIE_FILE = '/home/ubuntu/weibo_cookies.txt';
const TEST_CONTENT = '这是一条来自自动化脚本的测试微博 🤖 #测试 #自动化';
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function postWeibo() {
console.log('🌐 正在启动浏览器...');
const browser = await puppeteer.launch({
...getLaunchOptions(),
headless: true,
});
try {
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 900 });
// 读取并设置 Cookie
console.log('🍪 正在加载 Cookie...');
const cookieContent = fs.readFileSync(COOKIE_FILE, 'utf-8');
let cookies;
try {
cookies = JSON.parse(cookieContent);
// 如果是数组格式,直接使用
if (!Array.isArray(cookies)) {
// 如果是对象格式,转换为数组
cookies = Object.entries(cookies).map(([name, value]) => ({
name,
value,
domain: '.weibo.com',
path: '/'
}));
}
} catch (e) {
// 尝试解析为 name=value; 格式
cookies = cookieContent.split(';').map(pair => {
const [name, value] = pair.trim().split('=');
return { name, value, domain: '.weibo.com', path: '/' };
}).filter(c => c.name && c.value);
}
console.log(`📋 加载了 ${cookies.length} 个 Cookie`);
// 先访问微博主页,再设置 cookie
await page.goto('https://weibo.com', { waitUntil: 'networkidle2', timeout: 60000 });
await delay(2000);
// 设置 Cookie
for (const cookie of cookies) {
try {
// 确保必要的字段
const cookieToSet = {
name: cookie.name,
value: cookie.value,
domain: cookie.domain || '.weibo.com',
path: cookie.path || '/',
secure: cookie.secure || true,
httpOnly: cookie.httpOnly || false,
};
if (cookie.expirationDate) {
cookieToSet.expires = Math.floor(cookie.expirationDate);
}
await page.setCookie(cookieToSet);
} catch (e) {
// 忽略单个 cookie 设置错误
}
}
console.log('✅ Cookie 设置完成');
// 刷新页面,验证登录状态
console.log('🔄 刷新页面验证登录...');
await page.reload({ waitUntil: 'networkidle2', timeout: 60000 });
await delay(3000);
// 截图查看当前状态
await page.screenshot({ path: '/tmp/weibo_login/cookie_login_status.png' });
console.log('📸 已截图保存登录状态');
// 检查是否已登录(查找用户名或发布框)
const userName = await page.$eval('.user-name, .name, [class*="user"]', el => el.textContent).catch(() => null);
const postBox = await page.$('[class*="publish"], [class*="post"], textarea[class*="textarea"]').catch(() => null);
if (userName) {
console.log(`✅ 检测到用户名: ${userName.trim()}`);
}
if (postBox) {
console.log('✅ 找到发布框,准备发送微博...');
// 点击发布框
await postBox.click();
await delay(500);
// 输入内容
await postBox.type(TEST_CONTENT, { delay: 50 });
console.log('✍️ 已输入内容:', TEST_CONTENT);
// 查找发送按钮
const sendBtn = await page.$('[class*="send"], [class*="submit"], button:has-text("发送"), a:has-text("发送")').catch(() => null);
if (sendBtn) {
console.log('🖱️ 点击发送按钮...');
await sendBtn.click();
await delay(3000);
await page.screenshot({ path: '/tmp/weibo_login/after_post.png' });
console.log('📸 已截图保存发送结果');
console.log('\n✅ 测试微博发送完成!');
} else {
console.log('⚠️ 未找到发送按钮');
}
} else {
console.log('⚠️ 未找到发布框,可能未登录成功或页面结构不同');
// 尝试查找登录按钮
const loginBtn = await page.$('a:has-text("登录"), .login, [class*="login"]').catch(() => null);
if (loginBtn) {
console.log('❌ 检测到登录按钮,Cookie 可能已过期');
}
}
} catch (error) {
console.error('❌ 操作失败:', error.message);
await page.screenshot({ path: '/tmp/weibo_login/error.png' });
} finally {
await browser.close();
}
}
postWeibo().catch(console.error);