2

I want to run a JS script before the page load, so I have put it in tampermonkey. But the script doesnt persist after driver close. If I run the code again, the saved script is not there anymore. This is the code running selenium in python.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

opts = Options()
opts.add_extension("tampermonkey extension.zip")
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=opts)
driver.get("url")
# Add the JS script in Tampermonkey in the browser manually
driver.close()
netok
  • 181
  • 3
  • 9
  • Any particular reason for using Tampermonkey instead of executing the script with `driver.execute_script()`? – Dalvenjia Jan 23 '19 at 14:33
  • @Dalvenjia I want to run a JS script before the page load. AFAIK, `driver.execute_script()` doesnt guarantee that. – netok Jan 23 '19 at 14:34

1 Answers1

3

To persist any extension or particular settings after a driver "recycle" your only option is to have a custom profile already configured with whatever you need and tell selenium to use that profile.

In Chrome here's a good answer: How to load default profile in chrome using Python Selenium Webdriver?

In Firefox is directly supported by Selenium: https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.firefox.webdriver see the first parameter to the webdriver.Firefox() constructor https://selenium-python.readthedocs.io/api.html#selenium.webdriver.firefox.firefox_profile.FirefoxProfile

Dalvenjia
  • 1,953
  • 1
  • 12
  • 16