Is there a way to use PhantomJS in Python?
Question: I want to use [PhantomJS](http://phantomjs.org/) in
[Python](http://www.python.org/). I googled this problem but couldn't find
proper solutions.

I find `os.popen()` may be a good choice. But I couldn't pass some arguments
to it.

Using `subprocess.Popen()` may be a proper solution for now. I want to know
whether there's a better solution or not.

Is there a way to use PhantomJS in Python?


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

  1. Install [NodeJS](http://nodejs.org/)
  2. Using Node's package manager install phantomjs: `npm -g install phantomjs`
  3. install selenium (in your virtualenv, if you are using that)

After installation, you may use phantom as simple as:

    
    
    from selenium import webdriver
    
    driver = webdriver.PhantomJS() # or add to your PATH
    driver.set_window_size(1024, 768) # optional
    driver.get('https://google.com/')
    driver.save_screenshot('screen.png') # save a screenshot to disk
    sbtn = 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:

  * <http://selenium-python.readthedocs.org/en/latest/api.html>
  * [How do I set a proxy for phantomjs/ghostdriver in python webdriver?](http://stackoverflow.com/questions/14699718/how-do-i-set-a-proxy-for-phantomjs-ghostdriver-in-python-webdriver/15699530#15699530)
  * <http://python.dzone.com/articles/python-testing-phantomjs>

