|
| 1 | +from selenium import webdriver |
| 2 | +from selenium.webdriver.support.ui import WebDriverWait |
| 3 | +from selenium.webdriver.support import expected_conditions as EC |
| 4 | +from selenium.webdriver.common.by import By |
| 5 | +from os import listdir |
| 6 | +from os.path import isfile, join |
| 7 | +from requests_oauthlib import OAuth2Session |
| 8 | +import json |
| 9 | + |
| 10 | + |
| 11 | +def __get_client_secret_file__(filename): |
| 12 | + json_data = open(filename) |
| 13 | + d = json.load(json_data)["web"] |
| 14 | + json_data.close() |
| 15 | + return d |
| 16 | + |
| 17 | + |
| 18 | +def get_access_token(username, password, client_id = "", client_secret = "", scope= [], driver = None): |
| 19 | + |
| 20 | + if driver == None: |
| 21 | + driver = webdriver.Chrome() |
| 22 | + |
| 23 | + auth_uri = "https://accounts.google.com/o/oauth2/auth", |
| 24 | + token_uri = "https://accounts.google.com/o/oauth2/token" |
| 25 | + authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth" |
| 26 | + redirect_uri = 'https://localhost:8080/' |
| 27 | + |
| 28 | + google = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope) |
| 29 | + |
| 30 | + authorization_url, state = google.authorization_url(authorization_base_url, access_type="offline", prompt="select_account") |
| 31 | + |
| 32 | + driver.get(authorization_url) |
| 33 | + |
| 34 | + username_elem = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, 'identifierId'))) |
| 35 | + username_elem.send_keys(username) |
| 36 | + driver.find_element_by_id("identifierNext").click() |
| 37 | + |
| 38 | + password_elem = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.NAME, 'password'))) |
| 39 | + password_elem.send_keys(password) |
| 40 | + driver.find_element_by_id("passwordNext").click() |
| 41 | + |
| 42 | + if len(WebDriverWait(driver, 3).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="view_container"]/form/div[2]/div/div/div/ul/li[1]/div')))) != 0: |
| 43 | + driver.find_element_by_xpath('//*[@id="view_container"]/form/div[2]/div/div/div/ul/li[1]/div').click() |
| 44 | + |
| 45 | + |
| 46 | + next_btn = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, 'submit_approve_access'))) |
| 47 | + next_btn.click() |
| 48 | + |
| 49 | + wait = WebDriverWait(driver, 10) |
| 50 | + wait.until(lambda driver: redirect_uri in driver.current_url) |
| 51 | + |
| 52 | + redirect_response = driver.current_url |
| 53 | + |
| 54 | + google.fetch_token(token_uri, client_secret=client_secret, authorization_response=redirect_response) |
| 55 | + |
| 56 | + driver.close() |
| 57 | + |
| 58 | + return google |
0 commit comments