I have a lot of files to download so I'm trying to automate it with python and Selenium. (Accessing the site's API is not an option; I would have done that if I could have.)
The only element I can't get the script to find is the actual download button. (I get "NoSuchElementExists" error regardless of the method used to identify it.)
Here is the parent element with the two buttons. The second one is the one I want to select.
<div class="Transactions_csvButtonsContainer__dhv_J">
<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
</svg>
<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
</div>
I have gone into F12 Developer mode in both Firefox and Chrome and copied the XPATH and CSS Selector queries for the element, pasting them into the below code:
download_button = driver.find_element(by=By.XPATH, value=
"//*[@id='__next']/div/div[3]/div[1]/a[1]/div/div[1]/div[2]/svg[2]")
download_button = driver.find_element(by=By.CSS_SELECTOR, value=
"div.Transactions_bubblesAndCSVContainer__RxEX5: nth - child(1) > div:nth - child(2) > svg: nth - child(2)")
I'm not crazy about either of these methods because they are pretty brittle. The parent element (div) is not interactable. How can I get this script to recognize the download button?
In such an error I would recommend to approach it using XPath and Explicit Wait. Try importing first of all the needed packages:
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
Now, initialize the driver. I'm using Chrome, so:
driver = webdriver.Chrome()
driver.get('URL_OF_YOUR_PAGE') # Replace with the actual URL
Finally, wait for the element to be present and interactable:
try:
# wait for the container div to be present
wait = WebDriverWait(driver, 10)
container = wait.until(EC.presence_of_element_located(
(By.CLASS_NAME, 'Transactions_csvButtonsContainer__dhv_J')))
# find the second SVG element within the container
download_button = container.find_elements(By.TAG_NAME, 'svg')[1]
# click the download button
download_button.click()
except Exception as e:
print(f"An error occurred: {e}")
finally:
driver.quit()
I'm using exception handling so if any error occurs and those steps couldn't work, you could try debugging or other strategies. Keep me updated, hope it helps!