2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Webサイト内の特定のHTML部品に含まれる文字数を算出する

2
Last updated at Posted at 2023-09-20

個人的な需要があったので書きました。

1.事前準備

brew install node
npm install node-fetch jsdom

2.コード

count_characters.mjs
import fetch from 'node-fetch';
import { JSDOM } from 'jsdom';

async function countCharacters(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Failed to fetch URL: ${url}`);
    }

    const html = await response.text();

    const dom = new JSDOM(html);
    // 抽出したいDOMを指定する
    const element = dom.window.document.querySelector('#example');

    if (element) {
      const characterCount = element.textContent.length;
      console.log(`Character count for ${url}: ${characterCount}`);
      return characterCount;  
    } else {
      console.log(`No element found for ${url}`);
      return 0;  
  } catch (error) {
    console.error(`Error processing URL ${url}: ${error.message}`);
    return 0;  
  }
}  
// ここに抽出したいURLを入れる
const urls = [
  'https://example.com/',
];

// 文字数の抽出と平均文字数を計算する
Promise.all(urls.map(url => countCharacters(url)))
  .then(characterCounts => {
    const totalCharacters = characterCounts.reduce((total, count) => total + count, 0);
    const averageCharacters = totalCharacters / characterCounts.length;

    console.log('Total characters:', totalCharacters);
    console.log('Average characters per URL:', averageCharacters);
  })
  .catch(error => console.error('Error:', error));

3.実行

ファイルのあるディレクトリ上で以下のコマンドを実行すると、

node count_characters.mjs

各記事の文字数、総文字数、1URLあたりの平均文字数を抽出できる。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?