Skip to content

Instantly share code, notes, and snippets.

@Dynnammo
Created September 20, 2023 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dynnammo/7d8932de23e4a56d416500dd6d861f13 to your computer and use it in GitHub Desktop.
Save Dynnammo/7d8932de23e4a56d416500dd6d861f13 to your computer and use it in GitHub Desktop.
Scrap a Metabase graph using Python + Selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
import time
from random import random
# Locators of the download button and png button when you're on the indicator page; may change depending future Metabase releases.
PNG_BUTTON_LOCATION = "//div[@class='css-5h017v e1g70d2s4']/button[4]"
DOWNLOAD_BUTTON_PATH = (
"//button[@type='button']"
"[@class='Button mx1 hide sm-show efd1v1s0 css-s3ioln emiw9oj2']"
)
def wait_few_seconds():
time.sleep(random()+0.5)
driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)
url = input('Enter Metabase URL: ')
username = input('Enter Metabase username: ')
password = input('Enter Metabase password: ')
# Connect to Metabase
print('Connection to Metabase...')
driver.get(url)
wait_few_seconds()
user_field = self.driver.find_element(By.NAME, "username")
password_field = self.driver.find_element(By.NAME, "password")
user_field.send_keys(os.environ['METABASE_USERNAME'])
wait_few_seconds()
password_field.send_keys(os.environ['METABASE_PASSWORD'])
wait_few_seconds()
password_field.send_keys(Keys.RETURN)
print('Connection to Metabase succeeded !')
# Retrieve file
id = input('Enter ID of the graph you want to retrieve: ')
driver.get(f'{url}/question/{id}')
## Click on the Download button
download_button = wait.until(EC.element_to_be_clickable((By.XPATH, DOWNLOAD_BUTTON_PATH)))
download_button.click()
## Click on the ".png" button
png_button = wait.until(EC.element_to_be_clickable((By.XPATH, PNG_BUTTON_LOCATION)))
png_button.click() # File is downloaded locally on your default download folder
# End session
driver.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment