LoginSignup
10
10

More than 5 years have passed since last update.

Selenium+PhantomJS+Pythonでdivの横幅をサーバ側で取得

Last updated at Posted at 2015-08-31

今更ネタですが。

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での表示結果とあってたのでこれでよさそう。
おしまい

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