如何在使用Selenium时禁用Javascript?

cho*_*bo2 18 javascript selenium

我想知道如何在使用selenium时禁用javascript,以便我可以测试服务器端验证.

我找到了这篇文章,但我不知道该怎么做.就像我制作这个javascript文件那么?

http://thom.org.uk/2006/03/12/disabling-javascript-from-selenium/

Ass*_*esh 21

如果您将WebDriver与FireFox一起使用,这是一种方法:

FirefoxProfile p = new FirefoxProfile();
p.setPreference("javascript.enabled", false);
driver = new FirefoxDriver(p);
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于新的硒和火狐。它以前可以工作,但现在不行。 (2认同)

mar*_*ark 9

编辑

与此同时,出现了更好的替代方案,请参阅其他答案,例如/sf/answers/524475311/.

原始答案

其他可能性是:

  • 编写应用程序以支持禁用JavaScript(是的,Web应用程序).
    听起来很疯狂?不是.在我们的开发过程中,我们正是这样做的,在没有JS的情况下实现功能,直到所有功能都在那里,然后用JS调整.我们通常在所有模板中提供一个钩子,它可以从单个点控制到基本上从Web应用程序本身关闭/打开的JS.并且,是的,如果没有启用JS,应用程序很难识别,但这是确保工作正常运行的最佳方法.对于这两个版本,我们甚至为它编写Selenium测试; NOJS和JS.NOJS如此快速地实现,与编写复杂的JS测试相比,它们无关紧要......
  • 修改相应的浏览器配置文件以禁用JS.即FF,你可以告诉Selenium使用哪个配置文件; 您可以正常加载此配置文件,在about:config中禁用JS并将此配置文件作为默认配置文件提供给Selenium RC.


Aar*_*hif 9

对于python来说,这是一个简单的答案.

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference("javascript.enabled", False);
driver = webdriver.Firefox(profile)
Run Code Online (Sandbox Code Playgroud)

  • 在 2018 年不起作用,但以下答案可以:/sf/answers/3617712591/ (2认同)

Lev*_*von 6

截至 2018 年,上述解决方案对我Firefox 61.0.1geckodriver 0.20.1.

这是一个有效的解决方案。

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")
Run Code Online (Sandbox Code Playgroud)

现在在搜索栏中键入javascript,您应该会看到以下内容。

在此处输入图片说明