【PhantomJS】clickした後のhtmlを取得する
こちらでとりあえず動かせたのでついでにボタンをクリックした後のhtmlも取得してみたのでメモ。htmlはボタンをクリックしたらテキストがページに追加されていく簡単なもの。
index.html
<!DOCTYPE html> <head><title>テスト</title></head> <body> <div id="content"></div> <button id="btn-add" onclick="add();">追加</button><br/> <script> function add() { document.getElementById("content").innerHTML += "テスト<br/>"; } </script> </body> </html>
click.js
var page = require('webpage').create(); var url = "http://example.com/index.html"; page.open(url, function() { page.evaluate(function() { // 3回クリックする var btn = document.querySelector("#btn-add"); var event = document.createEvent("MouseEvents"); event.initEvent("click", false, true); btn.dispatchEvent(event); btn.dispatchEvent(event); btn.dispatchEvent(event); }); setTimeout(function() { console.log(page.content); phantom.exit(); },3000); });
実行
$ ./node_modules/phantomjs/bin/phantomjs click.js <!DOCTYPE html><html><head><title>テスト</title></head> <body> <div id="content">テスト<br>テスト<br>テスト<br></div> <button id="btn-add" onclick="add();">追加</button><br> <script> function add() { document.getElementById("content").innerHTML += "テスト<br/>"; } </script> </body></html>
3回クリックしたので「テスト」というテキストがちゃんと3つ表示されてる。
以上です