LoginSignup
4
2

More than 5 years have passed since last update.

GASでXPATHを使いたかったらスプレッドシート関数IMPORTXMLがあるよ

Last updated at Posted at 2018-09-28

過去の失敗

しかし、素晴らしいスプレッドシート関数を知った。

IMPORTXML関数


IMPORTXML("https://en.wikipedia.org/wiki/Moon_landing", "//a/@href")
概要
XML、HTML、CSV、TSV、RSS フィード、Atom XML フィードなど、さまざまな種類の構造化データからデータをインポートします。
URL
検証するページの URL です。プロトコル(「http://」など)も含めます。
XPathクエリ
構造化データで実行する XPath クエリです。

解析したいページの要素をスプレッドシート上に展開

サンぷるとして適当に新宿の安全ナビを開いて、
https://www.gaccom.jp/safety/search/?p=13&c=104

Chromeあたりの開発モードで必要な箇所を見てみると、
image.png

だいたいのclassがわかります(今回の場合は、liタグのmdl-list__itemクラス)

ここまで来たら、スプレッドシート上に1行、関数を書くだけです。

=IMPORTXML("https://www.gaccom.jp/safety/search/?p=13&c=104", "//li[@calss='mdl-list__item']//h5[@calss='info_title']")

image.png

スクリプトエディタからスプレッドシート上のセルと読み込むだけ

function hoge(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test");
  var arr = sheet.getRange(1, 1, sheet.getLastRow(), 2 ).getValues();

  arr.map(function(e) {return e.filter(function(f) {Logger.log(f)})});
}

image.png

すっごい楽!

4
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
4
2