I'm trying to export a planner as an excel from Microsoft's Tasks/Planner website using python, selenium, and chrome. Selenium opens a new browser which lacks cookies and thus always gets prompted for credentials and - for my company - two-factor authentication. Based on other stack exchange posts, I have saved and used a cookie which resolved this issue. Is there a different and ideally better way to approach this problem? I'd just like to know.
Here's my code in case it helps someone facing a similar task.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os, time, datetime
import json
def save_cookie(driver, path): #https://stackoverflow.com/questions/45417335/python-use-cookie-to-login-with-selenium
with open(path, 'w') as filehandler:
json.dump(driver.get_cookies(), filehandler)
def load_cookie(driver, path):
with open(path, 'r') as cookiesfile:
cookies = json.load(cookiesfile)
for cookie in cookies:
cookie.pop("domain")
driver.add_cookie(cookie)
url = "https://tasks.office.com/path/to/planner"
menu_selector = '//button[@title="More. Navigate to other pages related to this plan."]'
save_selector = "Export plan to Excel"
#r = requests.Session()
driver = webdriver.Chrome(r"C:\Users\user\AppData\Roaming\Python\Python38\site-packages\chromedriver.exe")
#Go to domain cookies rely on
driver.get("https://tasks.office.com/")
#load cookies
load_cookie(driver, r"C:\Users\user\Downloads\cookies.json")
driver.get(url) #go to actual website
authenticated = 'definitive_text_segment_from_url' in driver.current_url
if not authenticated: #Login to refresh cookie if stale.
username = input("Please provide a username")
password = input("Please provide a password")
driver.find_element_by_name("loginfmt").send_keys(username)
driver.find_element_by_name("loginfmt").send_keys(Keys.RETURN)
driver.find_element_by_name("pf.username").send_keys(username)
driver.find_element_by_name("pf.pass").send_keys(password)
driver.find_element_by_name("pf.pass").send_keys(Keys.RETURN)
authentification_code = input("Please provide the authentification code.")
elem = driver.find_element_by_xpath(menu_selector)
elem.click() #clicks on three dots
elem = driver.find_element_by_name(save_selector)
elem.click() #clicks on export planner option and autosaves file
save_cookie(driver, r"C:\Users\user\Downloads\cookies.json")