Search code examples
pythonpython-3.xselenium-chromedrivertypeerrorchrome-options

How to input a File Path which is a variable as part of a String (Python)


I am trying to plug in a String variable in my Chromedriver's default download directory, as shown below:

path = str(os.getcwd())
pdf_path = str(path + '\pdf')


chrome_options = Options()
chrome_options.add_experimental_option('prefs',  {
    "download.default_directory": '%s',
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True,
    "profile.default_content_setting_values.automatic_downloads": 1
    }
%(path))

I am then faced with the following error:

TypeError: unsupported operand type(s) for %: 'dict' and 'str'

To the best of my knowledge, this is the correct syntax when it comes to plugging in a String variable using the %s. Problem seems simple and I cannot seem to find the solution, as after some research I did not come across any examples of anyone plugging in a '%s' inside of chrome driver options.


Solution

  • Python doesn't let you format a dictionary in that way. This is the way to format the dictionary. Try changing the line to this:

    "download.default_directory": f'{path}'
    

    The dictionary should now look something like this:

    chrome_options = ('prefs',  {
        "download.default_directory": f'{path}',
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "plugins.always_open_pdf_externally": True,
        "profile.default_content_setting_values.automatic_downloads": 1
        })