Splash can execute custom rendering scripts written in the Lua programming language. This allows us to use Splash as a browser automation tool similar to PhantomJS. Lua言語で記述されたカスタムレンダリングスクリプトを実行できるPhantomJS的なもの。 Lua言語はRedis, Nginx, Apache, World of Warcraft scripts,などのカスタムスクリプトの記述に使われている。
It is not doing exactly the same work - instead of saving screenshots to files we’re returning PNG data to the client via HTTP API. スクリーンショットをPNG形式で取得しWebAPIで返却する例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
functionmain(splash, args) splash:set_viewport_size(800, 600) splash:set_user_agent('Splash bot') local example_urls = {"www.google.com", "www.bbc.co.uk", "scrapinghub.com"} local urls = args.urls or example_urls local results = {} for _, url inipairs(urls) do local ok, reason = splash:go("http://" .. url) if ok then splash:wait(0.2) results[url] = splash:png() end end return results end
WebUI上でRender me!を実行すると、各サイトのスクリーンショットが表示される。
Calling Splash Methods
There are two main ways to call Lua methods in Splash scripts: using positional and named arguments. To call a method using positional arguments use parentheses splash:foo(val1, val2), to call it with named arguments use curly braces: splash:foo{name1=val1, name2=val2}:
functionmain(splash, args) -- Examples of positional arguments: splash:go("http://example.com") splash:wait(0.5, false) local title = splash:evaljs("document.title")
-- The same using keyword arguments: splash:go{url="http://google.com"} splash:wait{time=0.5, cancel_on_redirect=false} local title = splash:evaljs{snippet="document.title"}
for developer errors (e.g. incorrect function arguments) exception is raised;
for errors outside developer control (e.g. a non-responding remote website) status flag is returned: functions that can fail return ok, reason pairs which developer can either handle or ignore. If main results in an unhandled exception then Splash returns HTTP 400 response with an error message.
Splashのルールでは以下のルール。
開発者エラーは例外にする
開発者が制御できないエラーはstatusで返す
例外はerror()で明示的に発生させることができる。
1 2 3 4 5 6 7
functionmain(splash, args) local ok, msg = splash:go("http://no-url.example.com") ifnot ok then -- handle error somehow, e.g. error(msg) end end
functionmain(splash, args) -- a shortcut for the code above: use assert assert(splash:go("http://no-rul.example.com")) end
Sandbox
By default Splash scripts are executed in a restricted environment: not all standard Lua modules and functions are available, Lua require is restricted, and there are resource limits (quite loose though).