<button type="button"><span >Download CSV</span></button>
I am trying to click on the highlighted button 'Download CSV' having the above HTML code and save the csv file at some particular location, but I am not able to do so. The file is getting downloaded in Downloads folder.
My python code:
def scrape_data():
DRIVER_PATH = r"C:\chrome\chromedriver.exe"
driver = webdriver.Chrome(DRIVER_PATH)
driver.get('Link to the dashboard')
time.sleep(20)
buttons = driver.find_element(By.XPATH,"//button/span[text()='Download CSV']")
time.sleep(5)
driver.execute_script("arguments[0].click();", buttons)
driver.quit()
So please suggest a way to search via the button text) and save the file to a particular location??
CodePudding user response:
To download the file on specific location you can try like blow.
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_experimental_option("prefs", {
"download.default_directory": r"C:\Data_Files\output_files"
})
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
CodePudding user response:
- You should not use hardcoded sleeps like
time.sleep(20)
.WebDriverWait
expected_conditions
should be used instead. - Adding a sleep between getting element and clicking it doesn't help in most cases.
- Clicking element with JavaScript should be never used until you really have no alternative.
- This should work in case the button you trying to click is inside the visible screen area and the locator is unique.
def scrape_data():
DRIVER_PATH = r"C:\chrome\chromedriver.exe"
driver = webdriver.Chrome(DRIVER_PATH)
wait = WebDriverWait(driver, 30)
driver.get('Link to the dashboard')
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Download CSV')]"))).click()