How to change firefox profile preference after defining webdriver using Selenium and Python

2k views Asked by At

How to change profile preference after defining driver?

profile = webdriver.FirefoxProfile()

driver = webdriver.Firefox(firefox_profile=profile)

After some code need to set useragent

profile.set_preference("general.useragent.override", ua)

How to set it without defining new driver?

3

There are 3 answers

0
undetected Selenium On BEST ANSWER

As per the current implementation of Selenium once you configure the GeckoDriver with specific Capabilities and initialize the session to open a Browsing Context, you cannot change the capabilities runtime. Even if you are able to retrieve the runtime capabilities still you won't be able to change them back.

So, in-order to change the Firefox User Preference you have to initiate a new WebDriver session.

Note:However, you can change the for Firefox on each run and you can find a relevant discussion in How to change user agent for Firefox webdriver in Python?


Reference

Here is @JimEvans clear and concise comment (as of Oct 24 '13 at 13:02) related to proxy settings capability:

When you set a proxy for any given driver, it is set only at the time WebDriver session is created; it cannot be changed at runtime. Even if you get the capabilities of the created session, you won't be able to change it. So the answer is, no, you must start a new session if you want to use different proxy settings.


Outro

You can find a couple of relevant detailed discussions in:

0
GProst On

I believe it’s not possible but I found some workarounds explained in this article, not sure if those approaches are reliable though (or work at all): https://tarunlalwani.com/post/change-profile-settings-at-runtime-firefox-selenium/

0
titusfortner On

Actually, this exactly what the set_context() method is for.

https://github.com/SeleniumHQ/selenium/blob/selenium-4.8.0/py/selenium/webdriver/firefox/webdriver.py#L224-L247

For example:

driver.set_context("chrome")
driver.execute_script("Services.prefs.setStringPref('intl.accept_languages', 'es-ES');")
driver.set_context("context")

Make sure you switch back to "context" or else you won't be able to continue.