Skip to content

Instantly share code, notes, and snippets.

@shner-elmo
Created March 20, 2023 14:22
Show Gist options
  • Save shner-elmo/72cbd11fa6255d56a0cb949b286072ae to your computer and use it in GitHub Desktop.
Save shner-elmo/72cbd11fa6255d56a0cb949b286072ae to your computer and use it in GitHub Desktop.
A wrapper around Selenium's WebDriver which makes it easier to open and close a given window
from __future__ import annotations
import time
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class DriverWrapper(webdriver.Chrome):
"""
A wrapper around the Selenium-driver object
"""
def __init__(self) -> None:
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
service = Service(executable_path=ChromeDriverManager().install())
caps = DesiredCapabilities().CHROME
caps['pageLoadStrategy'] = 'none'
super().__init__(options=options, service=service, desired_capabilities=caps)
def switch_window_focus(self, tab_position: int) -> None:
"""
A browser can have multiple windows/tabs, but to perform an action on a specific tab you need to
make sure that selenium's focus is on that tab.
"""
self.switch_to.window(self.window_handles[tab_position])
def open_and_switch_window(self, url: str) -> None:
"""
Open a new window from the given url and switch the driver's focus to the new window
"""
self.execute_script(f'window.open("{url}");')
time.sleep(0.2)
self.switch_window_focus(tab_position=-1)
def close_last_window(self) -> None:
"""
Close all the windows except the first
"""
self.switch_window_focus(tab_position=-1)
self.close()
self.switch_window_focus(tab_position=-1)
@shner-elmo
Copy link
Author

selenium = "^4.8.2"
webdriver-manager = "^3.8.5"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment