0

<button class="css-obkt16-button" type="button"><span class="css-1mhnkuh">Download CSV</span></button>

I am trying to click on the highlighted button 'Download CSV' enter image description here 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??

ameesha gupta
  • 101
  • 11
  • 1
    There is an extra closing square bracket in your XPath. Remove it. Vote to close as typo – JaSON Dec 12 '22 at 09:27
  • @JaSON Yes thanks I did that, but the thing is I want to the file to get downloaded at some path. How can I do that?? – ameesha gupta Dec 12 '22 at 09:30
  • https://stackoverflow.com/questions/58432057/how-do-i-click-enter-when-a-save-as-window-is-open-with-selenium/58432097#58432097 – JaSON Dec 12 '22 at 11:10

2 Answers2

1

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)
Akzy
  • 1,817
  • 1
  • 7
  • 19
1
  1. You should not use hardcoded sleeps like time.sleep(20). WebDriverWait expected_conditions should be used instead.
  2. Adding a sleep between getting element and clicking it doesn't help in most cases.
  3. Clicking element with JavaScript should be never used until you really have no alternative.
  4. 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()    
Prophet
  • 32,350
  • 22
  • 54
  • 79