selenium自动化携带cookies模拟登陆豆瓣(解决iframe定位问题)

获取cookies:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/27 17:44
# @Author  : huni
# @File    : 豆瓣cookies.py
# @Software: PyCharm
from selenium import webdriver
from time import sleep
import json
if __name__ == '__main__':
    driver = webdriver.Chrome(executable_path='./chromedriver.exe')
    driver.maximize_window()
    driver.get('https://www.douban.com/')
    sleep(6)
    driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="anony-reg-new"]/div/div[1]/iframe'))  # 切换浏览器标签定位的作用域
    driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div[1]/a[1]').click()
    sleep(10)
    dictCookies = driver.get_cookies()  # 获取list的cookies
    jsonCookies = json.dumps(dictCookies)  # 转换成字符串保存
    with open('豆瓣_cookies.txt', 'w') as f:
        f.write(jsonCookies)
    print('cookies保存成功!')

然后登陆豆瓣:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/27 18:05
# @Author  : huni
# @File    : 携带cookies登录豆瓣.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json
def browser_initial():
    # chrome_options = Options()
    # chrome_options.add_argument('--headless')
    # browser = webdriver.Chrome(options=chrome_options)
    browser = webdriver.Chrome(executable_path='./chromedriver.exe')
    browser.maximize_window()
    browser.get(
        'https://www.douban.com/')
    return browser

def log_csdn(browser):
    with open('豆瓣_cookies.txt', 'r', encoding='utf8') as f:
        listCookies = json.loads(f.read())

    # 往browser里添加cookies
    for cookie in listCookies:
        cookie_dict = {
     
            'domain': '.douban.com',
            'name': cookie.get('name'),
            'value': cookie.get('value'),
            "expires": '',
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False
        }
        browser.add_cookie(cookie_dict)
    browser.refresh()  # 刷新网页,cookies才成功
    
if __name__ == "__main__":
    browser = browser_initial()
    log_csdn(browser)

大家如果觉得小编的代码有用,可以多多关注小编,
同时小编的公众号也开通了,大家可以关注下,后续进行粉丝回馈,大家一起学习python叭

selenium自动化携带cookies模拟登陆豆瓣(解决iframe定位问题)_第1张图片

打赏小编点这里哦

selenium自动化携带cookies模拟登陆豆瓣(解决iframe定位问题)_第2张图片

你可能感兴趣的:(selenium,定位,selenium,chrome,cookie,json)