Search code examples
pythonpandasseleniumiframescreen-scraping

How to click a box with selenium which i can't see its element?


I want to change the frametime in fxblue technical analysis from 1h (the default value) to 5m but i can't click its pop-up button. here is the code i tried:

import pandas as pd
import numpy as np
import csv
import os
from selenium import webdriver
driver = webdriver.Chrome(os.getcwd() + '/chromedriver')  
url = "https://www.fxblue.com/market-data/technical-analysis/EURUSD"
driver.get(url)
time.sleep(5)
timestamp = driver.find_element_by_xpath('//*[@id="TimeframeContainer"]').click()

at this point I can see the pop-up with the timeframes but I couldn't find a way to change the timeframe.


Solution

  • The elements in the Timeframe pop-up is in an iframe. Need to switch to frame to interact with the elements contained in it.

    # Imports required
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver.get("https://www.fxblue.com/market-data/technical-analysis/EURUSD")
    
    wait = WebDriverWait(driver,30)
    
    # Click on timestamp button.
    timestamp = wait.until(EC.element_to_be_clickable((By.ID,"txtTimeframe")))
    timestamp.click()
    
    # Switch to iframe.
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@class,'DialogInnerIframe')]")))
    
    # click on M5 button.
    fivemin = wait.until(EC.element_to_be_clickable((By.XPATH,"//div[@class='TimeframeItem' and text()='M5']")))
    fivemin.click()
    
    # Switch to default content to interact with other elements.
    driver.switch_to.default_content()