-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
54 lines (42 loc) · 1.74 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from dotenv import load_dotenv
from os import path
import re
import os
import pickle
def setup(login_url, target_url, email_element_id, password_element_id, submit_button_id):
'''
Using credentials stored in .env OR cookies stashed in cookies.pkl, navigates
to the desired web page & authenticates.
Args:
* login_url: The url of the login page
* target_url: The url that follows after successful authentication
* email_element_id: The HTML element id for the email input box
* password_element_id: The HTML element id for the password input box
* submit_button_id: The HTML element id for the login form's submission button
'''
driver = webdriver.Chrome()
driver.get(login_url)
if path.exists('cookies.pkl'):
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
print(cookie)
driver.add_cookie(cookie)
driver.get(target_url)
else: # No cookies found so must login
load_dotenv()
USERNAME = os.environ["USERNAME"]
PASSWORD = os.environ["PASSWORD"]
username = driver.find_element_by_id(email_element_id)
password = driver.find_element_by_id(password_element_id)
username.send_keys(USERNAME)
password.send_keys(PASSWORD)
driver.find_element_by_id(submit_button_id).click()
pickle.dump(driver.get_cookies(), open("cookies.pkl","wb"))
wait = WebDriverWait(driver, 60)
wait.until(EC.url_to_be(target_url))
return(driver)