Python Selenium 如何保存和设置网页的cookies

汤修贤
2023-12-01

保存网页的cookies。

代码如下:


#用来保存对象或者是变量到文件中
import pickle;




if __name__=='__main__':
    #进入网页
    url = 'https://www.bilibili.com/';
    from selenium import webdriver;
    broswer = webdriver.Chrome();
    broswer.get(url=url);
    input("Please login this page");


    #得到网页的cookies
    broswer.refresh();
    cookies = broswer.get_cookies();


    # 写入cookie
    with open('cookies','wb') as f:
        pickle.dump(cookies, f);

    #读取cookie

    print('You cookies is ::');
    with open('cookies','rb') as f:

        print('(*****************)');
        a=pickle.load(f);
        print(a);




读取保存好的cookies并且设置网页的cookies。

#读取cookie
import pickle;
# 读取保存的cookies
def readCookies():
    with open('cookies','rb') as f:

        print('(*****************)');
        a=pickle.load(f);
        print(a);
        return a;

if __name__ == '__main__':

    #打开网页
    from selenium import webdriver
    broswer = webdriver.Chrome();
    url='https://www.bilibili.com/';
    broswer.get(url);

    #删除原来的cookie
    broswer.delete_all_cookies();

    #设置新的cookies
    cookies = readCookies();
    for cookie in cookies:
        broswer.add_cookie(cookie);
    #刷新网页
    broswer.refresh();

    input('yes?');

 类似资料: