To save chromedriver session, I used this snippet of code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('user-data-dir= path to where to save session')
driver = webdriver.Chrome(executable_path='path to chromedriver.exe', chrome_options=options)
I tried to do the same thing with Firefox but it doesn't seem to work:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.add_argument('user-data-dir= path to where to save session')
driver = webdriver.Firefox(executable_path='path to geckodriver.exe', firefox_options=options)
Is this the right way to go or did I miss something?
Below is the manual process to create a new profile and start firefox using existing profile:
To create a new profile, execute command: firefox.exe -CreateProfile JoelUser
To create a new profile in another directory, execute command: firefox.exe -CreateProfile "JoelUser c:\internet\joelusers-moz-profile"
To start firefox using new profile, execute command: firefox.exe -P "Joel User"
Now, to achieve the same programmatically, I figured out that step no. 1 or 2 can be executed using subprocess and step no. 3 can be achieved by following https://stackoverflow.com/a/54065166/6278432
References:
firefox bug - unable to create new session using custom profile: https://github.com/mozilla/geckodriver/issues/1058
https://bugzilla.mozilla.org/show_bug.cgi?id=1421766
Firefox command line params - https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#user_profile
subprocess api doc - https://docs.python.org/3/library/subprocess.html
Related
I'm trying to use Selenium in Python to fill out a form, which is why I need it to run in an existing Firefox window where I'm logged in due to the sensitive login data. But I can't seem to find a way to prevent the driver launching in a new window where I am logged out. Is there a way to do this?
I've tried using options to set preference:
`from selenium.webdriver.firefox.options import Options
options = Options()
options.set_preference("browser.tabs.loadInBackground", False)
driver = webdriver.Firefox(options=options)`
I also tried using the -no-remote command on Firefox in cmd before running the script, but it didn't work either.
From chrome driver you can achieve this.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("user-data-dir=C:/Users/Designer1/AppData/Local/Google/Chrome/User Data/Profile 1")
driver = webdriver.Chrome(chrome_options=options,executable_path="C:\webdrivers\chromedriver.exe")
I've been trying for some time to get this function to work, but I've tried several ways and I still can't. can anybody help me?
My goal is to prevent multiple browsers from being opened, that is, to check if there is already an instance of selenium firefox already open and return it so that the already open window can be used.
I tried with webdriver.remote, but no success.
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from webdriver_manager.firefox import GeckoDriverManager
def getDriver():
if isAlreadyRunning() == False:
firefox_service = Service(GeckoDriverManager().install())
driver = webdriver.Firefox(service=firefox_service)
return driver
else:
# Get the driver from the previous instance
return driver
def isAlreadyRunning():
try:
# Checks if a previous instance already exists to avoid opening a new browser
return True
except:
print('Driver is not running')
return False
driver = getDriver()
driver.get('https://stackoverflow.com')
The last attempts were activating the option marionette.debugging.clicktostart in about:config, opening cmd and starting firefox with the options:
cd 'C:\Program Files\Mozilla Firefox\'
.\firefox.exe -marionette -start-debugger-server 2828
and the code snippet below:
firefox_service = Service(GeckoDriverManager().install(), service_args=['--marionette-port', '2828', '--connect-existing'])
driver = webdriver.Firefox(service=firefox_service)
But after several seconds, selenium.common.exceptions.TimeoutException error is thrown
I'm using:
Python 3.10.4
Selenium 4.5.0
The below snippet isn't exactly your solution, but it would show a prompt if more than one instance of firefox is commanded by the program to run. The prompt would look like this although this won't focus on the opened window, the code would start running on that already open instance of Firefox, avoiding the clutter of multiple instances.
options = Options()
options.add_argument("-profile")
options.add_argument(os.path.expanduser("~")+"/AppData/Local/Mozilla/Firefox/Profiles")
firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
browser = webdriver.Firefox(capabilities=firefox_capabilities, options=options , executable_path= 'Whatsapp-Automation\geckodriver\geckodriver.exe')
This code snippet would create a unique profile of Firefox, so all your logins if done here would also be saved here.
Note: These are the required imports
from selenium import webdriver
import os
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
use psutil to check if any geckodriver is opened
import psutil
for proc in psutil.process_iter():
if "geckodriver" in proc.name():
print("- found..")
and use that to check firefox
for proc in psutil.process_iter():
if "firefox" in proc.name():
print(proc.cmdline())
check cmdline if contain current args
Previously, I use to load and save cookies which is an inconvenient way for most websites. Instead, I use a User Profile to make it run flawlessly.
The problem is I able to load the User Profile but not save it. After I make some changes to the browser such as config addons, changing themes, logging into some websites, etc., exit Firefox via input('exit?') (see the code below), I reopen Firefox with the same User Profile and notice that nothing was saved to the User Profile (I use both methods, open Firefox and select the User Profile (via cmd "Firefox.exe -P"); rerun the script).
Selenium v3.14.0
Python v3.9.7
GeckoDriver v0.30.0 (64-bit)
Firefox v103.0.1 (64-bit)
import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
FireFoxPath = r"C:\\Program Files\\Mozilla Firefox\\firefox.exe"
DriverPath = r"BrowserDriver\geckodriver-v0.30.0-win64\geckodriver.exe"
FirefoxProfilePath = os.path.join(os.getcwd(), 'Playground_Temp')
# Initialize
options = webdriver.FirefoxOptions()
options.binary_location = FireFoxPath
options.set_preference('app.update.auto', False)
options.set_preference('app.update.enable', False)
capabilities = DesiredCapabilities.FIREFOX
capabilities["pageLoadStrategy"] = "none"
# Start Firefox
driver = webdriver.Firefox(
webdriver.FirefoxProfile(FirefoxProfilePath),
desired_capabilities=capabilities,
options=options,
executable_path=DriverPath
)
# Wait for user make changes
input('exit?')
# Quit Firefox
driver.quit()
The Selenium Chrome Webdriver does not load my default Chrome profile.
I already tried many other Stack Overflow solutions including changing the path (and using the local Chrome App, which gives a 'permission denied' Error).
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=~/Library/Application Support/Google/Chrome/Default")
options.add_argument("--profile-directory=Default")
driver = webdriver.Chrome()
driver.get("https://tagmanager.google.com/#/home")
assert "Google Analytics" in driver.title
account_element = driver.find_element_by_css_selector("div.account.card div#149385038 table")
accountPublicId = driver.find_element_by_css_selector("div#149385038 table td.account__public-id")
The result is still the same; it loads only a 'naked' Chrome Webdriver instead of loading the local default profile (I use everyday for work).
Update:
I don't know how or why but now, when I quit Chrome and start Chrome through the Python Script, Google Chrome starts with my profile but does not use the cookies I have in that profile.
I will see if I can add the cookies "manually" with an options.add_arguments.
Try this:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\ProfilePath") ##profile path
w = webdriver.Chrome(executable_path="C:\\chromedriver.exe", chrome_options=options)
you may try this
options.add_argument("user-data-dir=C:\\Test")
did not add anything to the
options arguments (looking via debugger it was an empty list)
options.arguments.append("user-data-dir=C:/test/") managed to update the list of arguments
and it worked.
I am using 3rd party software to create a fancy application GUI with several buttons.
Each buttons will execute different .py file/.exe file. For instance:-
btnYahoo = execute yahoo.py/yahoo.exe
btnGoogle = execute google.py/google.exe
So inside both py scripts is using chromedriver to launch Chrome Browser and redirect to specific URLs
google.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path=r'chromedriver.exe')
driver.get("https://www.google.com")
yahoo.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path=r'chromedriver.exe')
driver.get("https://malaysia.yahoo.com/?p=us")
So if I execute both scripts above, it will launch 2 chrome browser.
Therefore, my concern is how can I check is webdriver.Chrome is running?
If so, then assign the webdriver.Chrome to a variable, so that I can open new tab and do further automate script progress.
For example of expected result:
Execute google.py - A new chrome browser is open and redirect to
www.google.com
Execute yahoo.py - If webdriver.Chrome is executed/existed, then assign the browser to driver variable. Else launch new browser
Thanks for advance information.
I was able to do so by checking if driver.session_id was None.