add injectionCookie

fix
This commit is contained in:
rsgltzyd 2024-07-30 21:23:35 +08:00
parent 7ff9cc663f
commit a8e451a8c2
4 changed files with 26 additions and 31 deletions

View File

@ -1,15 +0,0 @@
import { launch } from 'puppeteer';
import 'dotenv/config.js'
import { injectionCookie } from './utils/userUtils';
(async () => {
const browser = await launch({ headless: true, args: [`--window-size=1920,1080`], defaultViewport: { width: 1920, height: 1080 } });
const page = await browser.newPage();
// 注入cookie
const webUrl = 'https://www.zhihu.com/hot';
const cookieFileUrl = './data/zhihu.json';
await injectionCookie(page, webUrl, cookieFileUrl);
await browser.close();
})();

26
examples/zhihu.js Normal file
View File

@ -0,0 +1,26 @@
import { launch } from 'puppeteer';
import 'dotenv/config.js'
import { injectionCookie } from '../utils/userUtils.js';
(async () => {
const browser = await launch({ headless: false, args: [`--window-size=1920,1080`], defaultViewport: { width: 1920, height: 1080 } });
const page = await browser.newPage();
// 注入cookie
const webUrl = 'https://www.zhihu.com/hot';
const cookieFileUrl = './data/zhihu.json';
await injectionCookie(page, webUrl, cookieFileUrl);
const hotItems = await page.$$('.HotList-list .HotItem');
// console.log(hotItems);
console.log("========");
for (const hot in hotItems) {
if (Object.hasOwnProperty.call(hotItems, hot)) {
const element = hotItems[hot];
const textContent = await page.evaluate(node => node.textContent.trim(), element);
console.log(textContent);
}
}
// await browser.close();
})();

View File

@ -1,15 +0,0 @@
import { launch } from 'puppeteer';
import fs from 'fs';
import 'dotenv/config.js';
import { injectionCookie } from './utils/userUtils.js';
(async () => {
const browser = await launch({ headless: false, devtools: true, args: [`--window-size=1920,1080`], defaultViewport: { width: 1920, height: 1080 } });
const page = await browser.newPage();
const webUrl = 'https://www.zhihu.com/hot';
const cookieFileUrl = './data/zhihu.json';
await injectionCookie(page, webUrl, cookieFileUrl);
// browser.close();
})();

View File

@ -30,7 +30,6 @@ export async function injectionCookie(page, webUrl, cookieFile) {
try {
await page.goto(webUrl);
const cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf-8'));
console.log(cookies);
await page.setCookie(...cookies);
await page.goto(webUrl);
} catch (error) {