【发布时间】:2018-08-08 01:08:26
【问题描述】:
我想用无头铬和 puppeteer 实现什么:
- 登录某个网站
- 导航到 pdf 文件
- 下载到服务器
Headless chromium 无法导航到 pdf 文件,根据这个错误: https://bugs.chromium.org/p/chromium/issues/detail?id=761295
所以我尝试从当前 puppeteer 会话中获取 cookie 并通过 https.get 请求传递它们,但不幸的是没有成功。
我的代码:
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://login-page', { waitUntil: 'networkidle0' });
await page.type('#email', 'email');
await page.type('#password', 'password');
await page.click('input[type="submit"]');
await page.waitForNavigation({ waitUntil: 'networkidle0' });
// following line throws an error with headless mode
// await page.goto('https://url-with-pdf-accessible-only-after-login');
// I'm trying to convert cookie object to cookie string to pass it with headers
const cookies = await page.cookies();
let cookieString = '';
for (index in cookies) {
const cookie = cookies[index];
for (key in cookie) {
cookieString += key + '=' + cookie[key] + '; ';
}
}
// following code save me empty file (0 bytes)
const file = fs.createWriteStream('file.pdf');
https.get({
hostname: 'host-with-pdf-file',
path: '/path-to-pdf-accessible-only-after-login,
headers: {
'Cookie': cookieString,
}
}, res => {
res.pipe(file);
});
我做错了吗?
有没有其他方法可以将 pdf 文件从 url(需要身份验证)保存到服务器?
【问题讨论】:
-
你能用
request-promise-native这样的库试试吗?第一件事是确保您以正确的格式发送 cookie,使用库会更容易。第二件事是检查手动下载 PDF 时发出的 HTTP 请求。标题中是否有Referer或会话 ID 或其他内容?
标签: node.js puppeteer google-chrome-headless