原创  无密码登录 cookie 保活、有效性校验

分类: 2019-05-02T19:22:20    16人阅读   
import datetime
import json
import threading
import time
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

import app
from exts import db
from model.models import CookiePool
from selenium.webdriver.support.ui import WebDriverWait


class CookieService:
    def __init__(self):
        self.options = webdriver.FirefoxOptions()
       # self.options.add_argument('--headless')
        self.browser = webdriver.Firefox(executable_path=r'F:\Program Files (x86)\webdriver\geckodriver.exe',
                                         firefox_options=self.options)
        self.lock = threading.Lock()

    def test(self):
        print("running")
        self.keep_alive()

    def keep_alive(self):
        print('cookie 保活'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        global currentid
        try:
            with app.app.app_context():
                if self.lock.acquire():
                    result = CookiePool.query.filter(
                        CookiePool.updateAt <= datetime.datetime.now() + datetime.timedelta(minutes=-5),
                        CookiePool.isValid.__eq__('Y')).order_by(
                        CookiePool.updateAt.desc()).all()

                    for cookies in result:
                        self.browser.get(cookies.rootUrl)
                        cookie = json.loads(cookies.cookie)
                        for item in cookie:
                            self.browser.add_cookie(item)
                        self.browser.get(cookies.validUrl)
                        currentid = cookies.id
                        WebDriverWait(self.browser, 50).until(
                            EC.presence_of_element_located(
                                (By.CSS_SELECTOR, cookies.validTarget)))
                        CookiePool.query.filter_by(id=currentid).update(
                            {'updateAt': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())})
        except Exception as ex:
            print(str(ex))
            with app.app.app_context():
                CookiePool.query.filter_by(id=currentid).update({'isValid': 'N'})
                db.session.commit()
            app.app.logger.error("cookie keep Alive exception"+str(currentid), exc_info=True)
        finally:
            self.lock.release()


分享到: