How can I download a file on a click event using selenium?
Find the link using find_element(s)_by_*
, then call click
method.
from selenium import webdriver
# To prevent download dialog
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/tmp')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')
browser = webdriver.Firefox(profile)
browser.get("http://www.drugcite.com/?q=ACTIMMUNE")
browser.find_element_by_id('exportpt').click()
browser.find_element_by_id('exporthlgt').click()
Added profile manipulation code to prevent download dialog.
Download all files on a click event
You can avoid .click and concatenate the name onto base url and .get which will download all. Specify path to chromedriver if not on environmental path.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
base = 'http://biokb.ncpsb.org/AllerGAtlas/index.php/Home/Download/gene/genesymbol/'
d = webdriver.Chrome()
d.get('http://biokb.ncpsb.org/AllerGAtlas/index.php/Home/Browse/?fbclid=IwAR2RPwrnsT7zR9SEdU0PW-eJ7HAelg6WRyn23-hCjTrNCEOb1uOMd_qG3ns')
links = [base + item.text for item in WebDriverWait(d,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#geneTable td:nth-of-type(1)")))]
for link in links:
d.get(link)
d.quit()
Download with python selenium
In the website I click on a button that opens a small sub-window
Here you've mentioned that you are opening a new sub window where you've to click the button to download. But you are not switching to that window. Hence not able to find that element.
Use driver.window_handles
to get handle to the opened window and switch to that window using driver.switch_to_window()
then try clicking on the button to download.
You can see how to handle multiple windows in python selenium in this stackoverflow link.
EDIT:
So it seems there were some issues in your code. Like the locator for download buttons next to chess board and the one after that were incorrect. I've corrected the locator's with proper xpath
and also made little change in chrome_options
. You just have to change the download.defualt_directory
to a path in you machine and the below code will work:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("prefs", {
"download.default_directory": r"C:\Users\Thanthu Nair\Downloads\Test",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
})
driver = webdriver.Chrome("./chromedriver", options=chrome_options)
website = "https://www.chess.com/ccc"
driver.get(website) # loads the page
driver.maximize_window()
# This closes a sub-window that opens automatically
element = driver.find_element_by_class_name("form-button-component")
element.click()
download = driver.find_element_by_xpath("//i[@title='Download']")
download.click()
# Click to download
download.find_element_by_xpath("//button[normalize-space()='Download Game (PGN)']").click()
Download a file in IE using Selenium
So, the problem was that the cursor gets stuck sometimes when you call the click() function. So as a solution I used the Robot class to move my cursor and click on the export button and then I used Robot class to press Alt+S, which is a keyboard shortcut to save a file in IE.
To click on the button I used
try
{
Robot robot = new Robot();
Thread.sleep(2000);
robot.mouseMove(coordinates.getX()+100,coordinates.getY()-400);
Thread.sleep(2000);
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
catch (AWTException e)
{
e.printStackTrace();
}
To get the coordinates in the above snippet I used the following line
Point coordinates = driver.findElement(By.id("id")).getLocation();
System.out.println("Co-ordinates"+coordinates);
And to press Alt+S I used the following code
try
{
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
}
catch (AWTException e)
{
e.printStackTrace();
}
Related Topics
Generating a List of Random Numbers, Summing to 1
Convert Pandas Dataframe to Nested JSON
How to Put Individual Tags for a Matplotlib Scatter Plot
Label Python Data Points on Plot
Merging Several Python Dictionaries
Python and Pip, List All Versions of a Package That's Available
Combine Pool.Map with Shared Memory Array in Python Multiprocessing
Python Class Instance Variables and Class Variables
Use Cases for the 'Setdefault' Dict Method
Python String Prints as [U'String']
Combining Two Sorted Lists in Python
How Could I Use Requests in Asyncio
Extracting Date from a String in Python
How to Intercept Calls to Python's "Magic" Methods in New Style Classes
How to Save a Trained Model in Pytorch