【发布时间】:2024-05-04 19:55:02
【问题描述】:
这里是初级 JS。我计划从多个站点收集 cookie,因此我想将以下内容转换为 Node.js 辅助函数。
const chrome = require('chrome-cookies-secure');
const puppeteer = require('puppeteer');
const url = 'https://www.*.com';
const getCookies = (callback) => {
chrome.getCookies(url, 'puppeteer', function(err, cookies) {
if (err) {
console.log(err, 'error');
return
}
console.log(cookies, 'cookies');
callback(cookies);
}, 'Profile 6') // e.g. 'Profile 2'
}
// find profiles at ~/Library/Application Support/Google/Chrome
getCookies(async (cookies) => {
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
await page.setCookie(...cookies);
await page.goto(url);
await page.waitFor(5000);
browser.close()
});
上面的代码使用来自 Chrome 的 cookie 启动 puppeteer。
我在下面尝试将其作为一个函数,以便我可以轻松传递下面的任何 url。
helper.js
const chrome = require('chrome-cookies-secure');
module.exports.get_cookies = async (url) => {
chrome.getCookies(url, 'puppeteer', function(err, cookies) {
if (err) {
console.log(err, 'error');
return
}
console.log(cookies, 'cookies');
return Promise.resolve(cookies);
}, 'Profile 1') // e.g. 'Profile 2'
}
*.js
run = async () => {
var helper = require('./helper.js')
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
const url = 'https://www.*.com/';
var cookies = await helper.get_cookies(url);
console.log('got cookies');
await page.setCookie(...cookies);
await page.goto(url);
await page.waitFor(5000);
browser.close()
}
run()
问题是在控制台记录 cookie 后执行暂停。我不确定如何解决此问题。当我 ^C 时,js 并没有告诉我它在执行什么,它只是中断了。
更新
感谢Molda,我能够得到返回的cookies。现在正在尝试处理 Promise 拒绝。
got cookies
(node:53555) UnhandledPromiseRejectionWarning: TypeError: page.setCookie is not iterable (cannot read property Symbol(Symbol.iterator))
at run (/Users/paragbaxi/Documents/GitHub/safeshifter/libs/example_local_cookies.js:39:16)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:53555) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:53555) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[
{
name: 'token',
value: '3.oUjlqQnJzd0UiLCJleHBpcmVzIjoiMjAxOS0xMi0yNVQwMzo0NTo0My4wMDBaIiwibG9nZ2VkT3V0IjpmYWxzZSwic2NvcGVzIjpbIioiLCJlbWFpbCJdfQ==',
expires: 13284873942637332,
domain: '.*.com',
path: '/',
Secure: true
}
] cookies
【问题讨论】:
-
函数
get_cookies必须返回一个Promise,你调用resolve(cookies)这一行return cookies;in helper.js 并没有按照你的想法。 -
更新谢谢。现在有
UnhandledPromiseRejectionWarning
标签: node.js google-chrome cookies callback puppeteer