Is there a way to use PhantomJS in Python? Is there a way to use PhantomJS in Python? python python

Is there a way to use PhantomJS in Python?


The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is

  1. Install NodeJS
  2. Using Node's package manager install phantomjs: npm -g install phantomjs-prebuilt
  3. install selenium (in your virtualenv, if you are using that)

After installation, you may use phantom as simple as:

from selenium import webdriverdriver = webdriver.PhantomJS() # or add to your PATHdriver.set_window_size(1024, 768) # optionaldriver.get('https://google.com/')driver.save_screenshot('screen.png') # save a screenshot to disksbtn = driver.find_element_by_css_selector('button.gbqfba')sbtn.click()

If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to webdriver.PhantomJS(). Replace this:

driver = webdriver.PhantomJS() # or add to your PATH

... with the following:

driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')

References:


PhantomJS recently dropped Python support altogether. However, PhantomJS now embeds Ghost Driver.

A new project has since stepped up to fill the void: ghost.py. You probably want to use that instead:

from ghost import Ghostghost = Ghost()with ghost.start() as session:    page, extra_resources = ghost.open("http://jeanphi.me")    assert page.http_status==200 and 'jeanphix' in ghost.content


Now since the GhostDriver comes bundled with the PhantomJS, it has become even more convenient to use it through Selenium.

I tried the Node installation of PhantomJS, as suggested by Pykler, but in practice I found it to be slower than the standalone installation of PhantomJS. I guess standalone installation didn't provided these features earlier, but as of v1.9, it very much does so.

  1. Install PhantomJS (http://phantomjs.org/download.html) (If you are on Linux, following instructions will help https://stackoverflow.com/a/14267295/382630)
  2. Install Selenium using pip.

Now you can use like this

import selenium.webdriverdriver = selenium.webdriver.PhantomJS()driver.get('http://google.com')# do some processingdriver.quit()