[Node.js] cheerio で href の値を取得するサンプルコード
Node.js で jQuery ライクに使える cheerio で href の値を取得するサンプルコードをご紹介します。
- 公式サイト: cheerio | Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
- GitHub: cheeriojs/cheerio: Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
👎 間違った cheerio サンプルコード
以下のコードを実行すると undefined が出力されます。
const cheerio = require('cheerio'); const $ = cheerio.load('<a href="foo"></a>'); $().attr('href'); |
👍 正しい cheerio サンプルコード
メソッドチェーンで明示的に .find(‘a’) を実行後に .attr(‘href’) で href の値を取得しないといけません。
const cheerio = require('cheerio'); const $ = cheerio.load('<a href="foo"></a>'); $().find('a').attr('href'); |
以上、cheerio で href の値を取得するのに、ちょっと戸惑った現場からお送りしました。
参考情報
- cheerio.load('<a href="foo"></a>').root().attr('href') gives undefined · Issue #994 · cheeriojs/cheerio
- 公式サイト: cheerio | Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
- GitHub: cheeriojs/cheerio: Fast, flexible, and lean implementation of core jQuery designed specifically for the server.