import time

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from base.BaseCore import BaseCore

baseCore=BaseCore()
log = baseCore.getLogger()
cnx_ = baseCore.cnx
cursor_ = baseCore.cursor
agent = baseCore.getRandomUserAgent()
def flushAndGetToken():
    browser.refresh()
    wait = WebDriverWait(browser, 10)
    wait.until(EC.presence_of_element_located((By.ID, "loginLi")))
    cookie_list = browser.get_cookies()
    cookies = ''
    for cookie in cookie_list:
        cookies=cookies+cookie['name']+"="+cookie['value']+";"
    info = browser.page_source
    # res_2 = requests.get(year_url, proxies=ip)
    soup = BeautifulSoup(info, 'html.parser')
    #欢迎您，13683816984

    aEle = soup.find('li', attrs={'id':'loginLi'})
    text = aEle.text
    user_name = text.replace("欢迎您，","")
    #user_name = soup.select('a[id="loginLi"]')[0].text.replace("欢迎您，","")
    #user_name = soup.find('a', id_='loginLi').text.replace("欢迎您，","")
    if len(user_name)<3:
        log.info("没有登录成功，请重试")
        return
    cursor_.execute("insert into cpwsw_user (user,cookie,create_time,update_time,fenghao_time) values (%s,%s,now(),now(),DATE_SUB(NOW(), INTERVAL 1 DAY))",[user_name,cookies])
    cnx_.commit()
    log.info("保存成功")




opt = webdriver.ChromeOptions()
#opt.add_argument('user-agent=' + baseCore.getRandomUserAgent())
#opt.add_argument('user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')
opt.add_argument('user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')





opt.add_argument("--ignore-certificate-errors")
opt.add_argument("--ignore-ssl-errors")
opt.add_experimental_option("excludeSwitches", ["enable-automation"])
opt.add_experimental_option('excludeSwitches', ['enable-logging'])
opt.add_experimental_option('useAutomationExtension', False)
#opt.binary_location = r'C:/Program Files/Google/Chrome/Application/chrome.exe'
opt.binary_location = r'C:/Program Files/Google/Chrome/Application/chrome.exe'
chromedriver = r'E:/chromedriver_win32/117/chromedriver.exe'
service = Service(chromedriver)
browser = webdriver.Chrome(options=opt, service=service)
url = "https://wenshu.court.gov.cn/"
browser.get(url)
# 手机登录
#等200秒后在获取cookie保存到数据库
time.sleep(60)
flushAndGetToken()
cursor_.close()
cnx_.close()
baseCore.close()