0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[GAS] 動的ページをスクレイピングする

Posted at

きっかけ

GASは静的ページなら簡単にスクレイピングできるが、動的ページはそれができないのでPhantomJSCloudという外部サービスを使う。

PhantomJSCloud

APIキーの取得方法はまた後日
無料:1日に500回

完成コード

function phantomJSCloudScraping(URL) {
  //スクリプトプロパティからPhantomJsCloudのAPIキーを取得する
  let key = PropertiesService.getScriptProperties().getProperty('PHANTOMJSCLOUD_ID');

  //HTTPSレスポンスに設定するペイロードのオプション項目を設定する
  let option ={
    url: URL,
    renderType: "HTML",
    outputAsJson: true
  };
  
  //オプション項目をJSONにしてペイロードとして定義し、エンコードする
  let payload = JSON.stringify(option);
  payload = encodeURIComponent(payload);
  
  //PhantomJsCloudのAPIリクエストを行うためのURLを設定
  let apiUrl = "https://phantomjscloud.com/api/browser/v2/" + key + "/?request=" + payload;
  
  //設定したAPIリクエスト用URLにフェッチして、情報を取得する。
  let response = UrlFetchApp.fetch(apiUrl);
  
  //取得したjsonデータを配列データとして格納
  let json = JSON.parse(response.getContentText());
  
  //APIから取得したデータからJSから生成されたソースコードを取得
  let source = json["content"]["data"];

  return source;
}

概説

引数:動的WebページのURL
戻り値:HTMLのソースコード

PHANTOMJSCLOUD_ID:PhantomJSCloudのAPIキー(スクリプトプロパティで設定)

躓いた事

というか複数ページのテストを1日に何度もやってると割とすぐに500回制限に引っかかったので、その日の動的ページを取得してGoogleDriveに保存してそれでテストしてました。

function createFile(fileName, content) {  
  var folder = DriveApp.getFolderById('フォルダID');
  var contentType = 'text/plain';
  var charset = 'utf-8';

  // Blob を作成する
  var blob = Utilities.newBlob('', contentType, fileName)
                      .setDataFromString(content, charset);

  // ファイルに保存
  folder.createFile(blob);
}

function todayPhantom() {
  let url = "対象URL";
  createFile("PhantomJsCloud_Raw.html",phantomJSCloudScraping(url));
}

フォルダIDのGoogleDriveのフォルダにPhantomJsCloud_Raw.htmlができるので、それでテストする。

まとめ

PhantomJSCloudを間に挟むだけなので、後は静的ページのスクレイピングと同じなので比較的簡単!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?