码迷,mamicode.com
首页 > 其他好文 > 详细

添加cookie绕过登陆

时间:2020-04-03 16:29:34      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:turn   cli   driver   stat   cookie   文件   bin   exp   是否有效   

添加cookie绕过登陆

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from selenium import webdriver
import time
import pickle


class SkipLogin(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(15)
        self.driver.maximize_window()

    def add_have_login_state(self):
        try:
            cookies = pickle.load(open("cookies.pkl", "rb"))
            for cookie in cookies:
                cookie_dict = {
                    "domain": ".yaozh.com",  # 火狐浏览器不用填写domain,谷歌要需要
                    name: cookie.get(name),
                    value: cookie.get(value),
                    "expires": "",
                    path: /,
                    httpOnly: False,
                    HostOnly: False,
                    Secure: False}
                self.driver.add_cookie(cookie_dict)
        except Exception as e:
            print(e)

    # 打开个人中心
    def open_personal_center(self):
        self.driver.get("https://www.yaozh.com/member/")

    def is_login(self):
        return self.driver.current_url is not "https://www.yaozh.com/member/"

    # 添加cookies到文件中
    def write_cookies(self):
        self.driver.get("https://www.yaozh.com/login/")
        user_name = self.driver.find_element_by_id("username")
        pwd = self.driver.find_element_by_id("pwd")
        login_button = self.driver.find_element_by_id("button")
        user_name.send_keys("13609083341")
        pwd.send_keys("ybeuofnw")
        login_button.click()
        time.sleep(5)
        pickle.dump(self.driver.get_cookies(), open("cookies.pkl", "wb"))
        time.sleep(5)
        self.driver.close()

    def main(self):
        self.open_personal_center()
        if self.is_login():
            self.add_have_login_state()
            # 这里要加一个判断cookie是否有效判断,可以通过页面判断
        time.sleep(5)
        self.open_personal_center()
        time.sleep(5)
        self.driver.close()


if __name__ == __main__:
    sl = SkipLogin()
    # sl.write_cookies()
    sl.main()

 

添加cookie绕过登陆

标签:turn   cli   driver   stat   cookie   文件   bin   exp   是否有效   

原文地址:https://www.cnblogs.com/lvchengda/p/12627064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!