Irmantas Želionis
Irmantas Želionis

Reputation: 2324

Using selenium at hosted app?

I want to click one button with my Django app that I have hosted at DigitalOcean.

Here it is how I do it offline:

import selenium.webdriver as webdriver

firefox = webdriver.Firefox()
firefox.get("http://www.hltv.org/match/2296366-gplay-gamers2-acer-predator-masters-powered-by-intel")

element = firefox.find_element_by_id("voteteam1")
element.click()

But can I use it online? Maybe there is other solution?

Upvotes: 1

Views: 453

Answers (2)

alecxe
alecxe

Reputation: 473803

If you tied up to Firefox or any other browser "with a head", the common approach is to start a "Virtual Display" with the help of PyVirtualDisplay which is a wrapper around Xvfb, Xephyr and Xvnc, see this answer for an example working code.


Another option would be to use a "headless" browser, such as PhantomJS. In this case, the change is usually very simple, replacing:

firefox = webdriver.Firefox()

with:

driver = webdriver.PhantomJS()

Assuming you have PhantomJS installed.

Demo:

>>> from selenium import webdriver
>>> driver = webdriver.PhantomJS()
>>> driver.get("http://www.hltv.org/match/2296366-gplay-gamers2-acer-predator-masters-powered-by-intel")
>>> driver.title
u'HLTV.org - Hot Match: GPlay vs Gamers2'

The third option (mine most favorite) would be use a remote selenium server, either your own, or provided by third-party services like BrowserStack or Sauce Labs. Example code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {'os': 'Windows', 'os_version': 'xp', 'browser': 'IE', 'browser_version': '7.0' }

driver = webdriver.Remote(
    command_executor='http://username:[email protected]:80/wd/hub',
    desired_capabilities=desired_cap)

driver.get("http://www.google.com")
if not "Google" in driver.title:
    raise Exception("Unable to load google page!")
elem = driver.find_element_by_name("q")
elem.send_keys("BrowerStack")
elem.submit()
print driver.title
driver.quit()

In case of BrowserStack or Sauce Labs you have an enormous amount of browsers and operating systems to choose from. Note that these are not free services and you would need a username and a key for this code to work.

Upvotes: 0

Vikas Ojha
Vikas Ojha

Reputation: 6950

You will need to use firefox as headless on a Linux box. The following articles should help -

http://www.installationpage.com/selenium/how-to-run-selenium-headless-firefox-in-ubuntu/

Upvotes: 1

Related Questions