zoukankan      html  css  js  c++  java
  • 跳过cookies访问

    from selenium import webdriver
    import time,os,json


    driver = webdriver.Chrome()
    driver.maximize_window()
    url = "https://www.cnblogs.com/"
    driver.get(url)

    #保存cookies到文件中
    def save_cookies(driver):
    project_path = os.path.dirname(os.getcwd())
    file_path = project_path +"/cookies"
    if not os.path.exists(file_path):
    os.mkdir(file_path)

    #从driver中获取cookies
    cookies = driver.get_cookies()

    #读取cookies
    with open(file_path + "Cnblogs.cookies",'w') as c:
    json.dump(cookies,c)
    print(cookies)

    def login():
    try:
    #登录按钮
    driver.find_element_by_xpath('//*[@id="span_userinfo"]/a[1]').click()
    time.sleep(1)
    driver.find_element_by_id("LoginName").send_keys('wenjing2019')
    time.sleep(1)
    driver.find_element_by_id('Password').send_keys('*****')
    time.sleep(1)
    driver.find_element_by_id('submitBtn').click()

    # 保存cookies到文件中
    save_cookies(driver)
    finally:
    time.sleep(2)


    def get_url_with_cookies():
    #个人中心界面https://home.cnblogs.com/u/wenjing2019/来验证是否cookies成功
    #获取cookies文件并读取
    project_path = os.path.dirname(os.getcwd())
    file_path = project_path + "/cookies"
    cookies_file = file_path + "Cnblogs.cookies"

    cn_cookies_file = open(cookies_file,"r")
    cn_cookies_file_str = cn_cookies_file.readline()

    #加载cookies信息
    cn_cookies_file_dict = json.loads(cn_cookies_file_str)

    #这个地方先访问网站,先删除旧的cookies,再把保存的cookies添加进去
    driver.get("https://www.cnblogs.com/")
    driver.delete_all_cookies()

    #将cookies信息添加到driver中
    for cookies in cn_cookies_file_dict:
    driver.add_cookie(cookies)

    #验证是否成功
    driver.get("https://home.cnblogs.com/u/wenjing2019/")


    if __name__=="__main__":
    login()
    get_url_with_cookies()
  • 相关阅读:
    LeetCode 1032. Stream of Characters
    LeetCode 872. Leaf-Similar Trees
    LeetCode 715. Range Module
    LeetCode 353. Design Snake Game
    LeetCode 509. Fibonacci Number
    LeetCode 632. Smallest Range Covering Elements from K Lists
    LeetCode 963. Minimum Area Rectangle II
    LeetCode 939. Minimum Area Rectangle
    LeetCode 727. Minimum Window Subsequence
    LeetCode 844. Backspace String Compare
  • 原文地址:https://www.cnblogs.com/wenjing2019/p/12195746.html
Copyright © 2011-2022 走看看