Puppeteer を実行していて、いつの日か以下の警告が出ていることに気付く。
どうやら近いうちに、「headless: true」の設定がデフォルトで新しいヘッドレスモードになるとのこと。
1 2 3 4 5 6 | Puppeteer old Headless deprecation warning: In the near feature `headless: true` will default to the new Headless mode for Chrome instead of the old Headless implementation. For more information, please see https://developer.chrome.com/articles/new-headless/. Consider opting in early by passing `headless: "new"` to `puppeteer.launch()` If you encounter any bugs, please report them to https://github.com/puppeteer/puppeteer/issues/new/choose. |
2023 年の 2 月くらいから警告が出ていたのでしょうか。
この警告は、将来的には意図しない挙動になったり、サポートされなくなることが予想されるため、早めに対処しておくのがベターですね。
今回はこの警告が出なくなるような対応をしていきます。
警告の原因
Chrome のヘッドレスモードが大幅に改善されたことと、「headless=new」が導入されたことがトリガーで出力されるようになったようですね。
新しいものを選択しようが、古いものを選択しようが、こだわりがなければ放置でもいいと思うのですが、警告が出るのは気持ち悪い。
警告の対応
ということで Puppeteer の場合は、以下のサンプルコードが提供されています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import puppeteer from 'puppeteer'; const browser = await puppeteer.launch({ headless: 'new', // `headless: true` (default) enables old Headless; // `headless: 'new'` enables new Headless; // `headless: false` enables “headful” mode. }); const page = await browser.newPage(); await page.goto('https://developer.chrome.com/'); // … await browser.close(); |
launch のコンストラクタに、headless を指定するようですね。
headlessの設定値 | 挙動 |
---|---|
true(default) | enables old Headless |
new | enables new Headless |
false | enables “headful” mode |
では、headless に new を指定してみましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | (async () => { const browser = await puppeteer.launch({ headless: 'new' }); const page = await browser.newPage(); await page.setExtraHTTPHeaders({ 'Accept-Language': 'xx', 'User-Agent': 'xxxxxx' }); await page.goto(url, { waitUntil: 'networkidle0' }); const res = await page.evaluate(() => { return document.body.outerHTML; }); console.log(res); await browser.close(); })(); |
想定通り、冒頭の警告が出力されなくなりました。
まとめ
ヘッドレスモードの警告について紹介してきました。
Selenium やコマンドラインでの操作でも似たようなものですが、Puppeteer のケースも無事に解決。
GitHub Actions など CI で定期実行させているような処理は、エラーの監視はしているものの警告は見逃しがちですよね。
今回は手動実行で気付けたものの、やはりログの監視はもう少し検討してみたいところです。