Selenium – How to set up automatic downloads and change the default directory

Yeah, as you might have noticed, I love Selenium and I can’t live without. Every piece of code I write needs to call Selenium… all right, that was me overreacting about it, but, you have got my point.

Download a file using Selenium is such a basic task. However, you don’t have access to where file is going to be downloaded or how to click on the confirmation box to proceed with the download. Well, Chrome allows you to change that using preferences, which in Selenium is called Capabilities or ChromeOptions. Firefox can also do it, but, Chrome has way more options for that.

This can be done using the “SetPreference” method of the WebDriver element, which is required to be done before you start the navigation, that means, before you call the Get “http://your.website.address”.

The code block below allows you to:

  1. Activate the automatic download (without confirmation)
  2. Change the default download directory to same as the workbook
Private Sub AbreEConfiguraOChrome()
    Dim driver As New Selenium.ChromeDriver
    driver.SetPreference "download.default_directory", Replace(ThisWorkbook.FullName, ThisWorkbook.name, "")
    driver.SetPreference "download.directory_upgrade", True
    driver.SetPreference "download.prompt_for_download", False
    driver.Get "http://endereco.do.seu.site"
    'aqui começa seu código
End Sub

Piece of cake, right? Ok, it took me a while to figure this out, but it’s there!

Enjoy it!

Tecnologia e Programação