Firefox browser wont open maximized and wont switch tabs using Selenium - python

I'm opening Firefox browser through selenium(3.141.0) on python 3.9, and it will always start minimized, even though in code I passed function .maximise_window() after opening the browser. When its started this way, it wont execute code to maximise and it wont execute code to switch tabs, and it wont even do it if im trying to switch tabs manually with my mouse.
If I immediately click on the initiated firefox browser on my taskbar when the program is started, it will function normally, but it will open my browsers home tab, and execute my code in new tab. Thats why you may see in code a part that closes that first tab. When i dont do it and when it starts "faulty", the home tab wont be opened.
Im also using the lenght of tabs as an indicator if the browser initiated faulty, where I tried to put it into loop and make it restart till it opens with 2 tabs, but it just wont unless I manually click it.
The only solution so far I can think of is kinda "hacky"...using pyautogui to scan my taskbar after initializing browser and clicking it fast, but I dont really like the idea.
The code goes through my company data warehouse site and manipulates it to download data.
Update
Other hacky solution I found is starting 2 browsers. First won't work, but second will. Meaning that browser works normally IF there is another Firefox browser open at the time.
Snippets of code:
from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
class DWH_browser:
def __init__(self):
self.browser = webdriver.Firefox()
self.browser.maximize_window()
self.browser.get("www.letskeepthecompanysiteasecret.org")
self.len_windows = len(self.browser.window_handles)
print(len(self.browser.window_handles))#this next part is used to close the extra tab when browser
#started normally and opens an extra tab
if len(self.browser.window_handles) == 2:
self.browser.switch_to.window(self.browser.window_handles[0])
self.browser.close()
self.browser.switch_to.window(self.browser.window_handles[0])
self.a = ActionChains(self.browser)
time.sleep(5)
DWH = DWH_browser()#and i initiate it in the code "normally"
#This was the other code I tried using to initate the browser and restart till its in 2 tabs, but not working
# issue_lenght = 1
# while issue_lenght == 1:
# DWH = DWH_browser()
# issue_lenght = DWH.len_windows
# if DWH.len_windows == 1:
# DWH.browser.quit()
# print("RESTARTING BROWSER")

Summarizing your issues:
Always start minimized.
Passed function maximise_window() after opening the browser.
Won't execute code to switch tabs.
To get rid of all these issues you need to ensure that:
Selenium is upgraded to current levels Version 4.4.0.
GeckoDriver is updated to current GeckoDriver v0.31.0 level.
Firefox Browser is updated to current firefox=103.0.2.
Additionally, you won't be needing self.browser.maximize_window() as firefox by default opens in a maximized mode.
Finally, trying to switch tabs manually with my mouse is a big no as the program execution may get interupted.

Related

Python selenium code seems to wait after calling javascript that display modal dialog box

I'm using Python and Selenium to write an automation script in Internet Explorer.
When the web page throws up some kind of modal dialog box, the Python code stops running and just waits for some action to be taken on the popup. After you press the "yes" or "no" button, then the Python code continues.
I believe the underlying Javascript function that is getting called (saveClicked()) is generating the popup box using this line of code:
var result=window.showModalDialog('whatever....')
Does anyone know how to handle this in Selenium? I want my code to click "ok" in this window or to just accept it. I tried right-clicking on the window to look at source code, etc. but those options are not given to me...the only options are "move/close".
I've looked to see if there is some kind of default IE capability in Selenium that will just automatically accept all modal dialog boxes but haven't found any. I also thought of maybe wrapping the call to the Javascript function with something that would somehow send a keystroke to the alert. I'm open to anything!
Here is the code: It never moves past the .execute_script line...it just sits there waiting.
print('Saving')
# I have to do this because I can't get the handle to the save button
# using any of the known Selenium methods but calling the JS works
driver.execute_script('saveClicked();')
print('Test')
driver.switch_to().alert().send_keys(Keys.ENTER)
The code just STOPS after the Javascript is executed and never moves to the print('test') line or any other code I put there.
Any python selenium code suggestions to solve this would be greatly appreciated.
one way: you can try to use Alert to manage popups
Alert(driver).accept()
otherwise you can see the active window or tab with:
#get current window handle
p = driver.current_window_handle
#get windows
chwd = driver.window_handles
driver.switch_to.window(chwd[1])
reference:
https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.alert
Try:
message = "saveClicked()" # or any other of your messages
driver.execute_script(f"alert(\"{message}\");")
driver.switch_to.alert.accept()

Python switch focus back to terminal from web browser with driver selenium

I am using selenium webdriver to open a webpage and fill out the form.
anyways In the middle of the code i need to provide input data in the terminal
but the focus still stays in the webbrowser, so i need to move mouse manulally back to the terminal.
is there anyway to switch focus back to terminal from the webbrowser?
sample code :
import time
from selenium import webdriver
driver = webdriver.Chrome() # Optional argument, if not specified will search path.
driver.get('https://www.seleniumeasy.com/test/basic-first-form-demo.html')
search_box = driver.find_element_by_id('user-message')
search_box.send_keys('John Rambo')
time.sleep(5) # Let the user actually see something!
test=input('please provide a number 0-9: \n') # I'd like the focus to switch back to the terminal
driver.quit()
Through Selenium - no. It's a library that communicates exclusively to a browser, through the WebDriver protocol. It can only send request to the browser, which may (or may not) execute them.
As such, it cannot communicate with anything outside it - the OS, and its app switching routines including.
For that you need some other library, that can either issue OS requests (switch app), or simulates keyboard/mouse inputs. But these are OS dependant, e.g. different ones for Windows, Mac or Linux.

Preventing Python webbrowser.open() from dominating screen and preventing other processes. Is it possible to open as minimised?

I am using webbroswer.open() in a loop to download multiple files at given intervals.
The issue I am having is that whenever the browser window opens, it becomes the primary window and thereby interrupts and disrupts my ability to use the computer. Downloading multiple files means this can last some time. The broswer continuously flashing open is obviously jarring.
Is there any way to instruct webbrowser to open the browser minimised by default or otherwise avoid this issue in some other ingenious way?
Much appreciated!
If you are open to using other modules I would urge you to look into selenium. This allows you to do many things, and one of them is to launch in headless mode (so as not to disturb you as it loads pages). The documentation is at:
https://selenium-python.readthedocs.io/
And you would be interested in the headless option
You would be advised though to make sure your script works without this enabled before you enable it though.
Sample code:
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
my_options = Options()
my_options.headless = True # set to False for debugging!!
browser = webdriver.Chrome(options=my_options)
browser.get('http://www.google.com')
print('Done.')
You will need to download the proper drivers (just follow the instructions on the link I posted) for whatever browser you'd like. I picked Chrome, but they have Edge, Firefox, and Safari browsers as well!

How to handle javascript alert/pop up window: Python+Selenium IE webdriver

The webpage I need to go to has a javascript popup message with an OK button that appears before the page can finish loading.
There's ways to get rid of the message by either clicking the button, pressing enter, pressing the x to close, or pressing ALT+F4. But all attempts to either click or press keys fails and just remains on the page with the popup.
I must be missing something.
Everything is current and installed, even the registry additions for the IE server executable.
Thanks
If this Java popup is generated by IE you could be able to handle it using Alert(driver).accept()
I have run into this issue a couple of times where the popup is not part of IE at all and this does not work. there are a couple different methods you can try to get around this:
try switching your browser to phantomJS (this is a headless browser that works with selenium and runs in the background so you will not be able to see what selenium does anymore but it often will eliminate popups and is good if you don't actually need to click the popup)
try using the mouse or keyboard packages to hit that button.

Python with selenium: rerun on pre-existing browser

I'm using Python with Selenium 2.44. When the test fails, I can't just uncomment all the code before the failure when debugging it, because the driver will not be declared for the browser. Therefore, whenever I try fixing something, I always have to open a new browser in the test case. This is rather... slow since I have to login, which adds an additional 30 seconds (not devastating, but annoying). I want to know if there's a way for me to just continue a session, or do something that allows me to start the test midway through (so if I have the webpage open already, I can just immediately start clicking things rather than opening a new browser). Is this possible?
For example, if I had something along the lines of:
driver = webdriver.Firefox()
driver.get("google.com")
driver.find_element_by_xpath("//input[#id='gbqfq']").send_keys("cats" + Keys.RETURN)
This should open Firefox, go to google, and search for cats. Pretend like there's a ton of stuff you have to do before you can actually make it to the google page, though. Now if it were to fail on the search for cats, the only way I would be able to test to see if I fixed the code would be to rerun the test (webdriver.Firefox() would open a new browser). Rather than that, assuming I'd still have google open, I'd like the selenium test to just start off on the previous browser and google page (therefore saying the first step in the code would be the send_keys("cats")). Is this possible?
I think that this was a similar question, but it didn't get checked off as answered: How to resume browser session or use existing browser window with Selenium-Python?
This one also seems similar, only pertaining to Java: How do I rerun Selenium 2.0 (webdriver) tests on the same browser?
Thanks.
Look into pdb: https://docs.python.org/2/library/pdb.html
Placing this in your code will stop the progression of the test as is until you tell it to continue in your shell.
Using your code snippit:
from pdb import set_trace
driver = webdriver.Firefox()
driver.get("google.com")
set_trace()
driver.find_element_by_xpath("//input[#id='gbqfq']").send_keys("cats" + Keys.RETURN)
will stop your execution after getting the url, allow you to tinker, and then continue from where the test left off.
Alternatively, while debugging, you can just remove the driver.quit() statement, wherever it happens to be, which will keep the browser open wherever your assertion failed. But if you're using a framework like Django with the LiveTestServer Client, you won't have access to browse the site further. pdb will allow you to keep the test server active.

Categories

Resources