Skip to content

Instantly share code, notes, and snippets.

@moonzlo
Last active August 19, 2019 22:43
Show Gist options
  • Select an option

  • Save moonzlo/64b27c9091ac80e76fbb4e10d6eb5161 to your computer and use it in GitHub Desktop.

Select an option

Save moonzlo/64b27c9091ac80e76fbb4e10d6eb5161 to your computer and use it in GitHub Desktop.
selenium contextmanager
@contextmanager
def selen(driver_patch: str, profile_patch: str, config='windows') -> webdriver.Chrome:
"""
Самый удобный метод использования веб драйвера =)
:param driver_patch: str: patch to chromedriver(exe)
:param profile_patch: str: the path to the folder storing cookies
:param config: str: operating system
:return: webdriver.Chrome
"""
def windows_conf():
options = webdriver.ChromeOptions()
options.add_argument(f'user-data-dir={profile_patch}')
driver = webdriver.Chrome(executable_path=driver_patch, chrome_options=options)
return driver
def linux_conf():
options = webdriver.ChromeOptions()
arguments = ('headless', '--no-sandbox', '--disable-dev-shm-usage', f'user-data-dir={profile_patch}')
for option in arguments:
options.add_argument(option)
driver = webdriver.Chrome(executable_path=driver_patch, chrome_options=options)
return driver
configs = {'windows': windows_conf, 'linux': linux_conf}
web_driver = configs.get(config)()
try:
yield web_driver
web_driver.close()
time.sleep(1)
web_driver.quit()
except Exception as error:
web_driver.close()
time.sleep(1)
web_driver.quit()
raise Exception(error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment