Files
Ubuntu 32b43f85bd a
2026-07-03 16:58:28 +08:00

200 lines
6.3 KiB
JavaScript

/**
* 使用 Cookie 登录微博 V2 - 直接访问发布页面
*/
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 = '这是一条来自自动化脚本的测试微博 🤖 #测试 #自动化 ' + new Date().toLocaleString();
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');
const cookies = JSON.parse(cookieContent);
console.log(`📋 加载了 ${cookies.length} 个 Cookie`);
// 先访问微博并设置 cookie
await page.goto('https://weibo.com', { waitUntil: 'domcontentloaded', timeout: 60000 });
// 设置 Cookie
for (const cookie of cookies) {
try {
await page.setCookie({
name: cookie.name,
value: cookie.value,
domain: cookie.domain,
path: cookie.path || '/',
secure: cookie.secure || false,
httpOnly: cookie.httpOnly || false,
...(cookie.expirationDate && { expires: Math.floor(cookie.expirationDate) })
});
} catch (e) {}
}
console.log('✅ Cookie 设置完成');
// 访问个人主页验证登录
console.log('🔄 访问个人主页验证登录...');
await page.goto('https://weibo.com/u/me', { waitUntil: 'networkidle2', timeout: 60000 });
await delay(3000);
await page.screenshot({ path: '/tmp/weibo_login/profile_page.png' });
console.log('📸 已截图个人主页');
// 获取页面标题和URL
const title = await page.title();
const url = page.url();
console.log(`📄 页面标题: ${title}`);
console.log(`🔗 当前URL: ${url}`);
// 检查是否在登录页面
if (url.includes('login') || title.includes('登录')) {
console.log('❌ Cookie 已过期,需要重新登录');
return;
}
// 尝试打开发布器
console.log('\n📝 尝试打开发布器...');
await page.goto('https://weibo.com/u/me?tabtype=weibo', { waitUntil: 'networkidle2', timeout: 60000 });
await delay(3000);
// 查找发布框 - 尝试多种选择器
const selectors = [
'textarea[title="微博内容"]',
'.W_input',
'[node-type="textEl"]',
'textarea[placeholder*="有什么新鲜事"]',
'textarea[placeholder*="想说什么"]',
'[class*="publish"] textarea',
'[class*="post"] textarea',
];
let postBox = null;
for (const sel of selectors) {
postBox = await page.$(sel);
if (postBox) {
console.log(`✅ 找到发布框: ${sel}`);
break;
}
}
// 如果没找到,尝试点击"发布"按钮
if (!postBox) {
console.log('🖱️ 尝试点击发布按钮...');
// 通过文本内容查找按钮
const allLinks = await page.$$('a, button, div[role="button"]');
for (const link of allLinks) {
const text = await page.evaluate(el => el.textContent, link);
if (text && (text.includes('发布') || text.includes('发微博'))) {
console.log(` 找到发布按钮: "${text.trim()}"`);
await link.click();
await delay(2000);
break;
}
}
// 再次查找发布框
for (const sel of selectors) {
postBox = await page.$(sel);
if (postBox) break;
}
}
if (postBox) {
console.log('✅ 准备发送微博...');
// 聚焦并输入
await postBox.click();
await delay(500);
await postBox.type(TEST_CONTENT, { delay: 30 });
console.log('✍️ 已输入:', TEST_CONTENT);
await delay(1000);
await page.screenshot({ path: '/tmp/weibo_login/before_send.png' });
// 查找发送按钮
let sendBtn = null;
// 先尝试标准选择器
const sendSelectors = [
'a[title="发布"]',
'[action-type="submit"]',
'[node-type="submit"]',
'.W_btn_a',
'button[type="submit"]',
];
for (const sel of sendSelectors) {
sendBtn = await page.$(sel);
if (sendBtn) {
const text = await page.evaluate(el => el.textContent, sendBtn);
console.log(` 找到发送按钮: "${text?.trim()}" (${sel})`);
break;
}
}
// 如果没找到,通过文本搜索
if (!sendBtn) {
const allBtns = await page.$$('a, button, div[role="button"]');
for (const btn of allBtns) {
const text = await page.evaluate(el => el.textContent, btn);
if (text && (text.includes('发送') || text.includes('发布'))) {
console.log(` 通过文本找到按钮: "${text.trim()}"`);
sendBtn = btn;
break;
}
}
}
if (sendBtn) {
await sendBtn.click();
console.log('🚀 已点击发送!');
await delay(5000);
await page.screenshot({ path: '/tmp/weibo_login/after_send.png' });
console.log('📸 已截图保存结果');
// 检查是否发送成功
const success = await page.$eval('.success, .W_tips, [class*="success"]', el => el.textContent).catch(() => null);
if (success) {
console.log('✅ 发送结果:', success);
}
console.log('\n🎉 测试微博发送流程完成!');
} else {
console.log('⚠️ 未找到发送按钮,请查看 /tmp/weibo_login/before_send.png');
}
} else {
console.log('⚠️ 未找到发布框');
await page.screenshot({ path: '/tmp/weibo_login/no_postbox.png' });
}
} catch (error) {
console.error('❌ 错误:', error.message);
try {
await page.screenshot({ path: '/tmp/weibo_login/error.png' });
} catch (e) {}
} finally {
await browser.close();
}
}
postWeibo().catch(console.error);