File dialogue not getting close after file is downloaded - python

I have written a code in python selenium that will login to Jira and then open another URL that is to download a report file.
Step 1- driver.get(jira.com) # I will login on this page
Step 2- driver.get('Another Jira URL.com\file.csv?somthing something....')# This URL will give me a csv file to download if I will put this in browser directly.
after step 2 It will open file dialogue it's downloading file in .temp format in download folder and after driver.quit() not closing file dialogue.

You need to set prompt_for_download is set to false, so that you would not see that download prompt at all. Create an options and pass them like below and then create object of chromedriver
Sample code :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_experimental_option("prefs", {
"download.default_directory": r"C:\Users\xxx\downloads\Test",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
})
driver = webdriver.Chrome(executable_path = driver_path, options = options)

Related

Selenium webdriver - prefs ignored when using specific Chrome profile

I read a lot of answers about setting a download directory for Chrome, but couldn't find anything when you want to save a file to a specific directory, different from the default one, and you are using a specific profile.
The below code works fine, and when I download a file, it gets saved to the intended downloadFolderPath:
downloadFolderPath = 'P:\\reports\\attachments'
options = webdriver.ChromeOptions()
preferences = {"download.default_directory": downloadFolderPath,
"directory_upgrade": True,
"safebrowsing.enabled": True }
options.add_experimental_option("prefs", preferences)
options.headless = False
browser = webdriver.Chrome(executable_path='chromedriver.exe', options=options)
# browse to the page, click download, etc.
But when I try to do the same, this time using a specific Chrome profile, by adding user-data-dir and profile-directory arguments:
downloadFolderPath = 'P:\\reports\\attachments'
options = webdriver.ChromeOptions()
options.add_argument(r'--user-data-dir=C:\\Users\\my.name\\AppData\\Local\\Google\\Chrome\\User Data')
options.add_argument(r'--profile-directory=Profile 5')
preferences = {
"download.default_directory": downloadFolderPath,
"directory_upgrade": True,
"safebrowsing.enabled": True
}
options.add_experimental_option("prefs", preferences)
options.headless = False
browser = webdriver.Chrome(executable_path='chromedriver.exe', options=options)
# browse the page and download the file
Chrome indeed gets opened with the chosen profile, but the file that I download gets saved under the user profile default directory, C:\Users\my.name\Downloads instead of the one that I defined (P:\reports\attachments). It seems therefore that the preferences passed with options.add_experimental_option("prefs", preferences) are ignored when a profile different from the default one is used.
Or is there any different argument that needs to be used when working with specific profiles?
For info, I am on Windows 10, Python 3.9, using Chrome 95.0.4638.54 and chromedriver.exe is 95.0.4638.17
Thanks

Selenium chromdriver saving files with .crdownload extension

Using the following selenium/chrome preferences, I can download a file to the same folder that I run the original python file from, and it works properly (file saves as download.xls)
DOWNLOAD_DIR = r'/mnt/ssd/rl-scrape/files/dev/dl/'
options = Options()
options.headless = True
options.add_argument("--incognito")
options.add_argument("--window-size=1920,1200")
options.add_argument("--disable-extensions")
options.add_experimental_option("prefs", {
"download.default.directory": DOWNLOAD_DIR,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True})
I understand that I've typo'd download.default_directory above. If I correct it, the file gets downloaded to the desired directory, but as download.xls.crdownload and not download.xls
Chrome adds the .crdownload extension while the download is in progress. Once the file is complete, it will rename the file to its proper name. As long as you see .crdownload, the download is not complete.
Add a time delay for the download process to finish before it quits the window. Worked for me.

Selenium file download complete callback?

I have this script that successfully downloads a file from a webpage, even headlessly thanks to this
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
# function to take care of downloading file
def enable_download_headless(browser,download_dir):
browser.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd':'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
browser.execute("send_command", params)
# instantiate a chrome options object so you can set the size and headless preference
# some of these chrome options might be uncessary but I just used a boilerplate
# change the <path_to_download_default_directory> to whatever your default download folder is located
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=1920x1080")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--verbose')
chrome_options.add_experimental_option("prefs", {
"download.default_directory": ".",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing_for_trusted_sources_enabled": False,
"safebrowsing.enabled": False
})
chrome_options.add_argument('--disable-gpu')
#chrome_options.add_argument('--disable-software-rasterizer')
# initialize driver object and change the <path_to_chrome_driver> depending on your directory where your chromedriver should be
driver = webdriver.Chrome(options=chrome_options)
# change the <path_to_place_downloaded_file> to your directory where you would like to place the downloaded file
download_dir = "."
# function to handle setting up headless download
enable_download_headless(driver, download_dir)
# get request to target the site selenium is active on
driver.get("https://www.thinkbroadband.com/download")
# initialize an object to the location on the html page and click on it to download
search_input = driver.find_element_by_css_selector('#main-col > div > div > div:nth-child(8) > p:nth-child(1) > a > img')
search_input.click()
#this won't work because the file isn't here yet
with zipfile.ZipFile('my_downloaded_file.zip', 'r') as zip_ref:
zip_ref.extractall('.')
file = open('my_downloaded_file')
for line in file:
print(line)
file.close()
I want to use the file I have just downloaded. Everything at the bottom after the button.click() is just an example - printing out the contents for instance. It would be even better if I didn't have to find the file by name - if I could just pass selenium an empty object or something along with a function to call when the download is complete where I can use the object. How can I do something like this?
This will check if "Show in Folder" is in the pages source, which will be there if a file has been downloaded. Useful for one file, could be modified to see how many times it exists and thus check for multiple files.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.headless = True
with webdriver.Chrome(options=options) as b:
# your code here
b.execute_script("window.open('');")
b.switch_to.window(b.window_handles[1])
b.get('chrome://downloads/')
x = b.page_source
if "Show in folder" in x:
print("Yes")
else:
print("No")

How to change the target directory for a screenshot using Selenium webdriver in Firefox or Chrome

I want to make a screenshot of a webpage and save it in a custom location using Selenium webdriver with Python. I tried saving the screenshot to a custom location using both Firefox and Chrome but it always saves the screenshot in the project dir. Here is my Firefox version:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.dir",
'C:\\Users\\User\\WebstormProjects')
binary = FirefoxBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe")
def foxScreen():
driver = webdriver.Firefox(firefox_binary=binary,
firefox_profile=profile)
driver.get("http://google.com")
driver.save_screenshot("foxScreen.png")
driver.quit()
if __name__ == '__main__':
foxScreen()
And here is my Chrome version:
from selenium import webdriver
options = webdriver.ChromeOptions()
prefs = {"download.default_directory": r'C:\\Users\\User\\WebstormProjects',
"directory_upgrade": True}
options.add_experimental_option("prefs", prefs)
chromedriver =
"C:\\Users\\User\\Downloads\\chromedriver_win32\\chromedriver.exe"
def chromeScreen():
driver = webdriver.Chrome(chrome_options=options,
executable_path=chromedriver)
driver.get("http://google.com")
driver.save_screenshot("chromeScreen.png")
driver.quit()
if __name__ == '__main__':
chromeScreen()
I have tried different notations for the location I want the screenshot saved to but that does not seem to help. What should I change so it does not save the screenshot to the project directory but to a given custom location?
You need to consider a couple of facts as follows:
profile.set_preference('key', 'value')
set_preference(key, value) sets the preference that we want in the firefox_profile. This preference is in effect when a specific Firefox Profile is invoked.
save_screenshot(filename)
As per the documentation save_screenshot(filename) saves a screenshot of the current window to a PNG image file. This method returns False if there is any IOError, else returns True. Use full paths in your filename.
Args:
filename: The full path you wish to save your screenshot to. This should end with a .png extension.
Usage:
driver.save_screenshot(‘/Screenshots/foo.png’)
So, save_screenshot(filename) expects the full path you wish to save your screenshot to. As you were using:
driver.save_screenshot("foxScreen.png")
Hence the screenshot was always saved within the project directory.
Solution
To save the screenshot in a different directory you need to pass the absolute path as follows:
driver.save_screenshot("./my_directory/foo.png")
Reference
You can find a detailed discussion in How to take screenshot with Selenium WebDriver
Could try adding a few more options. This worked for me:
prefs = {"download.default_directory": r"\download\directory",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True}

How can I disable file download in Webdriver ChromeProfile

I use Webdriver with Chromedriver on python.
I execute pages with automatic file downloading and I need to disable it.
What I need to set up in Chrome-driver download profile to disable automatic download?
I found next solution:
in CromeOption I created a folder that can't be created ("NUL"), so file can't be downloaded, but I can check everything I need on a page.
chrome_profile = webdriver.ChromeOptions()
profile = {"download.default_directory": "NUL", "download.prompt_for_download": False, }
chrome_profile.add_experimental_option("prefs", profile)
self.driver = webdriver.Chrome('chromedriver.exe',chrome_options=chrome_profile)

Categories

Resources