Pages

Thursday, 22 December 2022

How to auto save files using a custom Firefox profile-Selenium Python?

 


If you are new to PYTHON then first check the post on How to Install Python on windows and mac?, once installation is complete then only checkout the below Q&A


If you are preparing for Selenium-Python Interview then also check below Q&A:


Python Interview Question & Answers Set - 01

Python Interview Q&A Set - 02

Python Interview Q&A Set - 03

How to auto save files using a custom Firefox profile?

The first step is to identify the type of file you want to auto save.

To identify the content type you want to download automatically, you can use curl:

curl -I URL | grep "Content-Type"

Another way to find the content type is by using the requests module, you can use it like this:

import requests
content_type = requests.head('http://www.python.org').headers['content-type']
print(content_type)

Once the content type is identified, you can use it to set the firefox profile preference: browser.helperApps.neverAsk.saveToDisk

Here is an example:

import os

from selenium import webdriver

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", os.getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream")

browser = webdriver.Firefox(firefox_profile=fp)
browser.get("http://pypi.python.org/pypi/selenium")
browser.find_element_by_partial_link_text("selenium-2").click()

In the above example, application/octet-stream is used as the content type.

The browser.download.dir option specify the directory where you want to download the files.

No comments:

Post a Comment