How to create dynamic directory for downloads in Selenium Python?

Question:

I am creating a new directory for downloads in the setup class using the script:

import time
from os import getenv
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from dotenv import load_dotenv
from Login_actions import Login_activities
from Insights_actions import Insights_activities
from Locators import Locators
import pytest, os
from datetime import datetime


class Test_Insights():

    @pytest.fixture()
    def test_setup(self):
        #make new directory for downloads
        new_dir = r"D:/Selenium/Insights/" + datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        print(new_dir)
        if not os.path.exists(new_dir):
            os.makedirs(new_dir)

        #intiating chrome browser instance
        options=Options()
        options.add_argument('--start-maximized')
        # options.add_argument('--headless')
        prefs={"download.default_directory" : new_dir}
        options.add_experimental_option("prefs", prefs)
        self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=options)

        #load credentials
        load_dotenv()
        self.username = getenv("TOP_USERNAME")
        self.password = getenv("TOP_PWD")

        #exiting ceremonies
        yield
        self.driver.close()
        self.driver.quit()
        print("Test executed")

When I run this script I get the following error:

[2220:21976:0915/144810.074:ERROR:util.cc(129)] Can't create base directory: C:Program FilesGoogleGoogleUpdater

How do I make selenium create a base directory for downloads?

[Updated the code for more clarity]

Asked By: Libin Thomas

||

Answers:

I found a fix. I created the base directory manually and that resolved the error

Answered By: Libin Thomas
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.