经过一番研究,我找到了使用 puppeteer 无头浏览器的解决方案。理想情况下,我想要一个像 run-headless https://example.com/update 这样的命令,但需要登录,因此使用 puppeteer 驱动无头浏览器。
CentOS 7.6 的安装步骤:
1.安装铬
# cd
# mkdir install
# cd install/
# wget http://mirror.centos.org/centos/7/os/x86_64/Packages/vulkan-filesystem-1.1.97.0-1.el7.noarch.rpm
# yum localinstall vulkan-filesystem-1.1.97.0-1.el7.noarch.rpm
# wget http://mirror.centos.org/centos/7/os/x86_64/Packages/vulkan-1.1.97.0-1.el7.x86_64.rpm
# yum localinstall vulkan-1.1.97.0-1.el7.x86_64.rpm
# wget http://mirror.centos.org/centos/7/os/x86_64/Packages/liberation-fonts-1.07.2-16.el7.noarch.rpm
# yum localinstall liberation-fonts-1.07.2-16.el7.noarch.rpm
# vi /etc/yum.repos.d/google-chrome.repo
# cat /etc/yum.repos.d/google-chrome.repo
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/x86_64
enabled=1
gpgcheck=1
gpgkey=https://dl.google.com/linux/linux_signing_key.pub
# yum install google-chrome-stable
2。安装 node.js
# curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
# yum install nodejs
3.补丁/etc/sysctl.conf
这是在不禁用沙箱的情况下运行 puppeteer 所必需的:
# echo "user.max_user_namespaces=15000" >> /etc/sysctl.conf
# reboot
4.创建 run-hourly.js puppeteer 脚本
此节点脚本必须以普通用户身份运行,而不是 root:
$ cd /path/to/script
$ npm install --save puppeteer
$ npm install --save pending-xhr-puppeteer
$ mkdir userDataDir
$ vi run-hourly.js # (content below)
$ node run-hourly.js
run-hourly.js脚本的文件内容:
const config = {
userDataDir: __dirname + '/userDataDir',
login: {
url: 'https://www.example.com/login/',
username: 'foobar',
password: 'secret',
},
pages: [{
url: 'https://www.example.com/update/hourly',
pdfFile: __dirname + '/page.pdf'
}]
};
const puppeteer = require('puppeteer');
const { PendingXHR } = require('pending-xhr-puppeteer');
(async() => {
// initialize headless browser
const browser = await puppeteer.launch({
headless: true, // run headless
dumpio: true, // capture console log to stdout
userDataDir: config.userDataDir // custom user data
});
const page = await browser.newPage();
const pendingXHR = new PendingXHR(page);
// login
await page.goto(config.login.url, {waitUntil: 'load'});
await page.type('#loginusername', config.login.username);
await page.type('#password', config.login.password);
await page.click('#signin');
await page.waitForNavigation();
// load pages of interest
await Promise.all(config.pages.map(async (pageCfg) => {
await page.goto(pageCfg.url, {waitUntil: 'networkidle0'}); // wait for page load
await page.setRequestInterception(true); // intercept requests for next line
await pendingXHR.waitForAllXhrFinished(); // wait for all requests to finish
await page.pdf({path: pageCfg.pdfFile}); // generate PDF from rendered page
}));
await browser.close();
})();
5.将每小时作业添加到 cron
以与脚本所有者相同的用户身份安装 cron 作业
$ crontab -l
$ crontab -e
25 * * * * cd /path/to/script && node run-hourly.js > hourly.log 2>&1