今更ネタですが。
divの横幅(px)が欲しい。
ブラウザ側ならJS使って簡単にとれるけど、今回はサーバ側で欲しい。
divの横幅なので、決まるのはレンダリング後だったりすることもある。
なので、サーバ側でレンダリングする。
サーバにFirefoxを入れてSeleniumでなんとか、というのも昔やったけど、Firefoxのインストール時、ディスプレイ周りで時間かかったいやな思い出があるので、今回はブラウザとしてPhantomJS使ってみた。
PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
だそうです。すごいね。
PhantomJSいれる
PhantomJSのビルドはこれのとおりやればいい
http://phantomjs.org/build.html
今回のサーバがCentOS5だったせいか、 うまく通らず、 git checkout 1.9
に変えたらすんなりいった。急いでるのでひとまずこれでいいか……
Seleniumいれる
次に、これをSeleniumから叩きたいので
pip install selenium
seleniumからPhantomJSをいじる
from selenium import webdriver
url = 'http://hoge'
driver = webdriver.PhantomJS()
driver.get(url)
e = driver.find_element_by_xpath("//*[@class='hoge']")
print(e.size)
>>> {'width': 602, 'height': 2098}
手持ちのChromeでの表示結果とあってたのでこれでよさそう。
おしまい