pythonselenium-webdriver

Cannot find an element with Selenium in Python


From this url: https://ec.europa.eu/economy_finance/recovery-and-resilience-scoreboard/milestones_and_targets.html?lang=en

I want to click to the following button:

enter image description here

and then click View data table but I cannot find the corresponding element. The code I am using is the following:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://ec.europa.eu/economy_finance/recovery-and-resilience-scoreboard/milestones_and_targets.html?lang=en')
element = driver.find_element(By.XPATH, '//*[@id="highcharts-ldz37cw-0"]/svg/g[7]/g')
element.click()

The error I am getting is:

NoSuchElementException: Unable to locate element: //*[@id="highcharts-ldz37cw-0"]/svg/g[7]/g; For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception

What is possibly the problem?


Solution

  • I looked around the code and found a method viewData() that is called when you press View data table.

    We can directly call it for the first chart using this script: window.Highcharts.charts[0].viewData()

    And to do it in selenium:

    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
    
    driver = webdriver.Chrome()
    driver.get('https://ec.europa.eu/economy_finance/recovery-and-resilience-scoreboard/milestones_and_targets.html?lang=en')
    
    # wait until chart is loaded
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div#fulfillmentStatusBarChart > div[id^=highcharts]')))
    
    # show data table for ALL charts
    driver.execute_script('window.Highcharts.charts.forEach(ch => ch.viewData())')
    
    # select the data table
    table = driver.find_element(By.CSS_SELECTOR, 'table[id^=highcharts-data-table]') # div.highcharts-data-table
    print(table.text)