Kiddo
Kiddo

Reputation: 1990

Cannot run PhantomJS with Flask on Ubuntu VPS

I'm doing a testing unit that requires the tests to be run via web browser. I'm using Ubuntu VPS 14 with LAMP stack installed, mod_wsgi, selenium 2.44 and PhantomJS 1.9. I'm testing with the very simple code first:

from flask import Flask, request
from selenium import webdriver

app = Flask(__name__)
app.debug = True

@app.route("/test")
def test():
    url = "http://www.google.com"
    driver = webdriver.PhantomJS('./phantomjs')
    driver.get(url)
    result = driver.page_source
    driver.close()
    return result

if __name__ == "__main__":
  app.run() 

The code runs very smoothly on my local Ubuntu, it prints out the google page when I connect to: 127.0.0.1:5000/test . On my Ubuntu VPS, my have my flask already setup and running. Now i use the same code to be the index file (supposed all configs are OK and 'hello world' runs), I have 500 Internal Server Error when connecting to http://xxx.xxx.xxx.xxx/test

Apache log sends out the following error:

... service_args=service_args, log_path=service_log_path File "/usr/local/lib/python2.7/ddist-packages/selenium/webdriver/phantomjs/service.py", line 53, in init self._log = open(log_path, 'w') in > ignored Exception AttributeError: "'Service' object has no attribute '_log'" in > ignored

I changed the log_path for phatomJS but still have the same problem. However, if I open python console, doing line by line as following:

from selenium import webdriver
br = webdriver.PhantomJS('./phantomjs')
....

I got no error. It took me the whole day to fin the problem but I could't be able to fix it. Any ideas how to solve this problem?

Upvotes: 3

Views: 699

Answers (1)

Kiddo
Kiddo

Reputation: 1990

Figure out the problem, current phantomjs and init.py don't have enough permission to manipulate the service.py of ghostdriver. Here is the fix:

  1. Add a new user: "add username", then set "add username sudo"
  2. Login to the new user, make sure every command you run from now on starts with "sudo"
  3. In your flask application where init.py resides, create "ghostdriver.log" and "phantomjs" which is an executable file.
  4. Chmod both of them to 777 : init.py, ghostdriver.log and phantomjs
  5. Set the custom config in init.py for phantomjs:

    br = webdriver.PhantomJS(service_log_path='./ghostdriver.log', executable_path='./phantomjs')

That's it, now your selenium + flask + phantomjs is now working correctly.

Upvotes: 2

Related Questions