from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
from selenium.webdriver.edge.service import Service
import time, json

def create_driver():
    ip = {
        'https': 'https://127.0.0.1:1080',
        'http': 'http://127.0.0.1:1080'

    }
    edge_service = Service(r'D:\soft\msedgedriver.exe')
    edge_options = Options()
    # 开启开发者模式
    edge_options.add_experimental_option('excludeSwitches', ['enable-automation'])
    # 禁用启用Blink运行时的功能
    edge_options.add_argument('--disable-blink-features=AutomationControlled')
    edge_options.add_argument('--proxy-server=%s' % ip['http'])
    # prefs = {"profile.managed_default_content_settings.images": 2, 'permissions.default.stylesheet': 2}
    # edge_options.add_experimental_option("prefs", prefs)
    driver = webdriver.Edge(service=edge_service, options=edge_options)
    return driver


def login():
    driver = create_driver()
    un = 'zhk2058@163.com'
    pw = 'ZZM205899'
    driver.get(
        "https://sso.accounts.dowjones.com/login-page?client_id=5hssEAdMy0mJTICnJNvC9TXEw3Va7jfO&redirect_uri=https%3A%2F%2Fcn.wsj.com%2Fclient%2Fauth&response_type=code&scope=openid%20idp_id%20roles%20tags%20email%20given_name%20family_name%20uuid%20djid%20djUsername%20djStatus%20trackid%20prts%20updated_at%20created_at%20offline_access&ui_locales=zh-tw-x-cwsj-27-2&nonce=beaaad3a-6919-4893-8198-c3769d6d54af&state=73NKOEQds-P9ZH7w.ie3C279-7mV69dSbgfC_fu7R0sZqMkGovzhN3NJbUfU&resource=https%253A%252F%252Fcn.wsj.com%252F&protocol=oauth2&client=5hssEAdMy0mJTICnJNvC9TXEw3Va7jfO#!/signin")
    time.sleep(5)
    driver.find_element(By.XPATH, "//div/input[@name = 'username']").send_keys(un)
    # //*[@id="basic-login"]/div[1]/form/div[5]/div[1]/button[2]
    driver.find_element(By.XPATH, '//*[@id="basic-login"]/div[1]/form/div[5]/div[1]/button[2]').click()
    time.sleep(3)
    # //*[@id="password-login"]/div/form/div[5]/button
    driver.find_element(By.ID, "password-login-password").send_keys(pw)
    driver.find_element(By.XPATH, '//*[@id="password-login"]/div/form/div[5]/button').click()
    time.sleep(3)
    cookie = driver.get_cookies()
    return cookie, driver


if __name__ == '__main__':

    cookie, driver = login()
    cookies = {}
    for item in cookie:
        cookies[item['name']] = item['value']
    with open("wsj_cookie.txt", "w") as f:
        f.write(json.dumps(cookies))


