LoginSignup
10
3

More than 5 years have passed since last update.

Google Apps ScriptでHTMLテキストからDOMオブジェクトを生成したいが無理だった

Last updated at Posted at 2018-01-06

javascriptでよく使う次のようなDOMアクセス。

var x = document.getElementsByClassName("example");

GASのUrlfetchで得たContentからDOMオブジェクトを生成して同じように操作がしたい。

XmlService.parseでやってみる

RSSなどのXML文字列ならXmlService.parseを使って対処できるが、HTMLではXML構文にマッチしないのでエラーが出まくる。
ならばと、なんとかHTMLからXML構造に持っていこうとしたが、

  var r = UrlFetchApp.fetch("https://www.example.com");
  var text = r.getContentText()
  text = text.replace(/<link [\s\S]*?>/g,"");
  text = text.replace(/<meta [\s\S]*?>/g,"");
  text = text.replace(/<img [\s\S]*?>/g,"");
  text = text.replace(/<input [\s\S]*?>/g,"");
  text = text.replace(/<!--[\s\S]*?-->/g,"");
  text = text.replace(/ async/g,"");
  text = text.replace(/ selected/g,"");

  text = text.replace(/&url;/g,"");
  text = text.replace(/&raquo;/g,"");
  text = text.replace(/&nbsp;/g,"");

キリがないよ...

documentクラスでやってみる

テキストのHTMLをDOMに変換する方法として、ググるとよく出てくるのが、空のDIVオブジェクトを作ってそのinnerHTMLを更新する方法。

  var div = document.createElement('div');
  div.innerHTML = contentText;

うん、でも、サーバーサイドのjavascriptだから動かないね。

DOMを諦めて正規表現で対象となる部分を抽出

  var r = UrlFetchApp.fetch("https://www.example.jp");
  var text = r.getContentText()
  var res = text.match(/<li class="hogehoge">[\s\S]*?<\/li>/g);

でも汎用性ないねぇ。。。誰かいい方法を知りませんか。

10
3
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
10
3