python脚本获取网页第3方登录的cookies

以企业微信tapd网站为例,登录需要通过企业微信扫码,本文将讲述通过python脚本实现获取第3方登录cookies并将其保存到pc本地的方法,示例代码如下:

from selenium import webdriver
import requests,json,os
import time

def get_tapd_cookie():
    url_tapd='https://www.tapd.cn/cloud_logins/login'
    driver = webdriver.Chrome()  # 加载浏览器驱动,需提前将Chrome浏览器添加到系统环境变量
    driver.get(url_tapd)
    time.sleep(15)  #设置一个等待时间方便进行扫码登录操作
    cookie_items=driver.get_cookies()
    print(cookie_items)
    print(len(cookie_items))
    for i in cookie_items:
        if 'expiry'in i:
            i['expiry']=1672279757 #将cookies有效期延长
        else:
            pass
    print(cookie_items)
    return cookie_items

def save_cookie(data,encoding='utf-8'):
    with open('F:/Test/cookies.txt','w',encoding=encoding) as f:
        json.dump(data,f)

def load_cookie(encoding='utf-8'):
    if os.path.isfile('F:/Test/cookies.txt'):
        with open('F:/Test/cookies.txt','r',encoding=encoding)as f:
            user_cookie=json.load(f)
            #print(user_cookie)
            return user_cookie


if __name__ =='__main__':
    data=get_tapd_cookie()
    save_cookie(data)
    user_cookie=load_cookie()
    print(user_cookie)

 

posted @ 2022-09-02 19:02  沐小木  Views(90)  Comments(0Edit  收藏  举报