LoginSignup
2
2

More than 1 year has passed since last update.

Chrome拡張機能でスクレイピング結果をダウンロードする

Last updated at Posted at 2022-01-28

Chrome拡張機能のプロジェクトを作成する

ファイルを設置

任意のディレクトリに以下のファイルを設置する。
manifest.json
script.js

ディレクトリをChromeから読み込む

chrome___extensions_.png

1.拡張機能管理ページを開く。 (URLは→ chrome://extensions/)
2.「デベロッパーモード」をONにする。
3.「パッケージ化されていない拡張機能を読み込む」ボタンを押してディレクトリを選択する。

参考:Chrome拡張機能の作り方。誰でもかんたんに開発できる!

manifest.json

manifest.json
{
  "name": "Scrape Sample",
  "action": {},
  "manifest_version": 3,
  "version": "0.1",
  "description": "Scrape the web page",
  "permissions": [
    "activeTab",
    "scripting"
  ],
  "content_scripts": [
    {
      "run_at":"document_end",
      "matches": ["<all_urls>"],
      "js": ["jquery-3.6.0.min.js"
      ,"script.js"
      ]
    }
  ]
}

概要:
activeTab: 現在のタブで実行する。
document_end: ページ読み込み後に実行する。
all_urls: 全てのURLが対象。
js: マイ拡張機能ディレクトリのjquery-3.6.0.min.js、script.jsを実行する。
jQueryを利用する場合はダウンロードして設置する。
jQuery Download

スクリプト script.js

script.js
$(function(){
    // タイトルをファイルタイトルとして取得する
    var title = $('title').text();
    var str = "";
    // (全体取得だと順番が崩れたためeachにする)
    $('article p').each(function(idx,ele){
        // 空文字列の場合は飛ばす
        if ( $(this).text() == "" ) return true;
        if ( idx > 0 ) str += "\n";
        curtext = $(this).html();
        // brタグを改行に変更する
        curtext = curtext.replace(/<br>/g, "\n");
        // 文字列に追加する
        str += curtext;
    });

    // 取得した文字列でテキストファイルを作成
    const blob = new Blob([str],{type:"text/plain"});
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = title + '.txt';
    // aタグをクリックさせて自動ダウンロードする
    link.click();

});

拡張機能を読み込み(変更した場合はリロード)後に、対象ページを読み込むと、機能が実行される。

参考:JavaScript:ブラウザからローカルのテキストファイルの入出力

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