To download a file in Python using Selenium, use the urllib.request.urlretrieve() method to get the file from the supplied URL.
Example
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import urllib.request
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.maximize_window()
driver.get('http://autopract.com/selenium/download.html')
downloadUrl = driver.find_element(By.ID,"download")
urllib.request.urlretrieve(downloadUrl, "luffy.csv")
- We create a web driver instance with the Chrome driver in this code line.
- Then, using the web driver instance's get() method, we travel to the URL where the file is located.
- Using the webdriver instance's current_url field, we then retrieve the URL of the file to be downloaded.
- Finally, we utilize the urllib.request module's urlretrieve() method to download the file from the specified URL and store it as "luffy.csv" in the current working directory.
- Log in to post comments