当記事の目的
NodeJSでヤフーニュースの主要トピックを取得する。
NodeJSがインストールされていることを確認。
> node -v
v12.16.2
puppeteerパッケージをインストール
> npm i puppeteer
インストール済みのパッケージを確認
> npm list --depth=0
`-- puppeteer@2.1.1
ニュース取得スクリプトを作成
news.js
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://news.yahoo.co.jp/');
const itemSelector = '.topicsList_main li.topicsListItem a'
// ヤフーニュースページ内で主要トピックを取得
const newsList = await page.evaluate((itemSelector) => {
const news = [];
const nodes = document.querySelectorAll(itemSelector);
nodes.forEach(node => {
news.push(node.innerText);
})
return news;
}, itemSelector);
//表示
newsList.forEach(news => {
console.log(news);
});
// ブラウザを閉じる
await browser.close();
})();
実行
> node news
中国公船が領海侵入 2日連続
岐阜が「出口戦略」5指標示す
調停中断 親「子に会えない」
看護師と家族に誹謗中傷 神戸
正恩氏 プーチン氏に祝電
ソウル 遊興施設を営業禁止に
リトル・リチャード氏 死去
室井佑月と米山隆一氏 結婚へ