To automate the process of downloading tick history data for each currency pair across all months on the Exness website, you'll need to enhance your existing Selenium script. Below is a comprehensive guide and an updated script that accomplishes the following:
- Select Each Currency Pair: Iterate through all available currency pairs on the page.
- Iterate Through All Months: For each currency pair, select each month available for download.
- Trigger Downloads: Initiate the download for the selected currency pair and month.
- Handle Downloads: Configure the browser to handle downloads automatically without prompts.
Prerequisites
-
Install Selenium:
pip install selenium
-
Download WebDriver:
- For Chrome, download ChromeDriver and ensure it's in your system's PATH.
- Alternatively, specify the path to the
chromedriver executable in the script.
-
Set Up Download Directory:
Decide where you want the downloaded files to be saved.
Updated Script
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service as ChromeService # Use FirefoxService for Firefox
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import time
import os
# Configuration
URL = "https://www.exness.global/tick-history/" # Replace with the actual URL
CURRENCY_INPUT_XPATH = '//*[@id="instrument"]' # XPath for currency pair selection
MONTH_INPUT_XPATH = '/html/body/div[1]/div[1]/div/main/section[2]/div/div/div[4]/div/div/input' # XPath for month selection
DOWNLOAD_BUTTON_XPATH = '//*[@id="download-button"]' # Replace with the actual XPath of the download button
DOWNLOAD_DIR = os.path.join(os.getcwd(), "downloads") # Directory to save downloads
# List of months or the pattern to iterate over
MONTH_VALUES = [
"Exness_XAUUSDm_2024.zip",
# Add other month values here as needed
]
# List of currency pairs to iterate over
CURRENCY_PAIRS = [
"XAUUSD", # Example currency pairs
"EURUSD",
"GBPUSD",
# Add other currency pairs here
]
def setup_driver():
"""Set up the Chrome WebDriver with desired options."""
options = webdriver.ChromeOptions()
prefs = {
"download.default_directory": DOWNLOAD_DIR, # Set default download directory
"download.prompt_for_download": False, # Disable download prompts
"download.directory_upgrade": True,
"safebrowsing.enabled": True, # Enable safe browsing
}
options.add_experimental_option("prefs", prefs)
# Uncomment the next line to run in headless mode
# options.add_argument("--headless")
driver = webdriver.Chrome(options=options)
return driver
def wait_for_downloads(directory):
"""Wait until all files are downloaded in the directory."""
seconds = 0
dl_wait = True
while dl_wait and seconds < 300:
time.sleep(1)
dl_wait = False
for fname in os.listdir(directory):
if fname.endswith('.crdownload'):
dl_wait = True
seconds += 1
if seconds >= 300:
print("Download timed out.")
def select_currency_pair(driver, wait, currency_pair):
"""Select a currency pair from the dropdown."""
try:
instrument_input = wait.until(
EC.element_to_be_clickable((By.XPATH, CURRENCY_INPUT_XPATH))
)
instrument_input.click()
print(f"Clicked on the currency pair input for {currency_pair}.")
# Assuming that the dropdown becomes active and shows options
# You might need to adjust the way to select the currency pair
option_xpath = f"//li[contains(text(), '{currency_pair}')]"
option = wait.until(
EC.element_to_be_clickable((By.XPATH, option_xpath))
)
option.click()
print(f"Selected currency pair: {currency_pair}.")
except TimeoutException:
print(f"Failed to select currency pair: {currency_pair}.")
except NoSuchElementException:
print(f"Currency pair option not found: {currency_pair}.")
def select_month(driver, wait, month_value):
"""Select a month from the month selection input."""
try:
month_input = wait.until(
EC.element_to_be_clickable((By.XPATH, MONTH_INPUT_XPATH))
)
month_input.click()
print(f"Clicked on the month input to select {month_value}.")
# Depending on how the month selection works, you might need to iterate or find the option
# For example, if it's a dropdown, find the option by value or text
option_xpath = f"//li[contains(@class, 'MuiMenuItem-root') and @data-value='{month_value}']"
month_option = wait.until(
EC.element_to_be_clickable((By.XPATH, option_xpath))
)
month_option.click()
print(f"Selected month: {month_value}.")
except TimeoutException:
print(f"Failed to select month: {month_value}.")
except NoSuchElementException:
print(f"Month option not found: {month_value}.")
def trigger_download(driver, wait):
"""Click the download button to initiate the download."""
try:
download_button = wait.until(
EC.element_to_be_clickable((By.XPATH, DOWNLOAD_BUTTON_XPATH))
)
download_button.click()
print("Clicked the download button.")
except TimeoutException:
print("Download button not found or not clickable.")
except NoSuchElementException:
print("Download button element not found.")
def main():
# Create download directory if it doesn't exist
if not os.path.exists(DOWNLOAD_DIR):
os.makedirs(DOWNLOAD_DIR)
print(f"Created download directory at {DOWNLOAD_DIR}.")
# Initialize WebDriver
driver = setup_driver()
try:
# Navigate to the specified URL
driver.get(URL)
print(f"Navigated to {URL}.")
# Initialize WebDriverWait
wait = WebDriverWait(driver, 20) # Increased wait time for dynamic content
# Iterate through each currency pair
for currency in CURRENCY_PAIRS:
print(f"\nProcessing currency pair: {currency}")
select_currency_pair(driver, wait, currency)
# Iterate through each month value
for month in MONTH_VALUES:
print(f"\nSelecting month: {month}")
select_month(driver, wait, month)
# Trigger the download
trigger_download(driver, wait)
# Wait for the download to complete
wait_for_downloads(DOWNLOAD_DIR)
print(f"Download completed for {currency} - {month}")
# Optionally, add a short delay before the next iteration
time.sleep(2)
except Exception as e:
print(f"An error occurred during automation: {e}")
finally:
# Close the browser after all operations
driver.quit()
print("Browser closed.")
if __name__ == "__main__":
main()
Explanation of the Updated Script
-
Browser Configuration:
- Download Directory: The script sets a specific directory (
downloads) where all the downloaded files will be saved. This ensures that downloads are organized and can be easily managed.
- Download Preferences: The Chrome WebDriver is configured to automatically download files without prompting the user. This is crucial for automation to run seamlessly without manual intervention.
-
Functions Breakdown:
setup_driver(): Initializes the Chrome WebDriver with the specified download preferences. You can uncomment the headless option to run the browser in the background without a UI.
wait_for_downloads(directory): Monitors the download directory to ensure that all downloads are completed before proceeding. It checks for the presence of .crdownload files, which indicate ongoing downloads.
select_currency_pair(driver, wait, currency_pair): Handles the selection of each currency pair from the dropdown menu. It clicks on the currency input, waits for the dropdown options to appear, and selects the desired currency pair.
select_month(driver, wait, month_value): Handles the selection of each month. Similar to currency selection, it interacts with the month input and selects the appropriate month based on the provided value.
trigger_download(driver, wait): Clicks the download button to initiate the download of the selected currency pair and month.
-
Iterative Process:
- The
main() function orchestrates the entire process:
- Navigates to the specified URL.
- Iterates through each currency pair listed in
CURRENCY_PAIRS.
- For each currency pair, it iterates through each month listed in
MONTH_VALUES.
- For each combination, it selects the currency pair, selects the month, triggers the download, and waits for the download to complete before moving to the next iteration.
-
Handling Dynamic Elements:
- The script uses
WebDriverWait to wait for elements to become clickable or present in the DOM. This ensures that the script doesn't fail due to elements not being loaded yet.
- XPaths for dynamic selection (like currency pairs and months) are constructed based on the expected structure of the dropdown menus. You might need to adjust these XPaths based on the actual HTML structure of the Exness website.
Customizing the Script
-
Currency Pairs:
- Update the
CURRENCY_PAIRS list with all the currency pairs you intend to download data for. Ensure that the names match exactly with how they appear on the website.
-
Months:
- Update the
MONTH_VALUES list with all the month values you need. Ensure these values correspond to the value attributes used in the month selection input.
-
Download Button XPath:
- Replace
'//*[@id="download-button"]' with the actual XPath of the download button on the Exness website. You can locate this using browser developer tools by inspecting the download button element.
-
Handling Pagination or More Options:
- If the website uses pagination or dynamic loading for currency pairs or months, you might need to enhance the script to handle these scenarios, such as clicking a "Load More" button or scrolling.
-
Headless Mode:
- For faster execution and to run the script without opening a visible browser window, uncomment the
options.add_argument("--headless") line in the setup_driver() function.
Final Notes
-
Testing: Before running the script for all currency pairs and months, perform a test run with a single currency pair and month to ensure that the automation works as expected.
-
Delays: The script includes time.sleep(2) between iterations to provide a buffer. You can adjust or remove these delays based on the website's responsiveness.
-
Compliance: Ensure that automating downloads on the Exness website complies with their terms of service. Excessive automated requests might lead to IP blocking or other restrictions.
By following this guide and customizing the script as needed, you should be able to automate the downloading of tick history data for all desired currency pairs and months efficiently.