How to disable Javascript when using Selenium?

This is the simple answer, for python at least.

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference("javascript.enabled", False);
driver = webdriver.Firefox(profile)

Edit

In the meantime better alternatives did arise, please see the other answers e.g. https://stackoverflow.com/a/7492504/47573 .

Original answer

Other possibilities would be:

  • Write your application to support disabling JavaScript (yes, the web application).
    Sounds crazy? Isn't. In our development process we're doing exactly this, implementing features without JS until all are there, then spice up with JS. We usually provide a hook within all templates which can control from a single point to basically which JS off/on from the web application itself. And, yes, the application is hardly recognizable without JS enabled, but it's the best way to ensure things work properly. We even write Selenium tests for it, for both versions; NOJS and JS. The NOJS are so quickly implemented that they don't matter compared to what it takes to write sophisticated JS tests ...
  • Modify the appropriate browser profile to have JS disabled. I.e. for FF you can tell Selenium which profile to use; you can load this profile normally, disable JS in about:config and feed this profile as default profile to Selenium RC.

This is a way to do it if you use WebDriver with FireFox:

FirefoxProfile p = new FirefoxProfile();
p.setPreference("javascript.enabled", false);
driver = new FirefoxDriver(p);

As of 2018 the above solutions didn't work for me for Firefox 61.0.1 and geckodriver 0.20.1.

And here is a solution which works.

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

browser_exe = '/path/to/firefox/exe'
browser_driver_exe = '/path/to/geckodriver/exe'

firefox_binary = FirefoxBinary(browser_exe)

profile = webdriver.FirefoxProfile()
profile.DEFAULT_PREFERENCES['frozen']['javascript.enabled'] = False
profile.set_preference("app.update.auto", False)
profile.set_preference("app.update.enabled", False)
profile.update_preferences()

driver = webdriver.Firefox(
    executable_path=browser_driver_exe,
    firefox_binary=firefox_binary,
    firefox_profile=profile,
)

driver.get("about:config")

Now in the search bar type javascript and you should see the following.

enter image description here