python3 selenium 登录douban,获取cookie

selenium登录豆瓣流程:

1. 进入豆瓣登录页面
2. 切换到**子框架**,定位**用户,密码**输入框. 并输入数据,再**定位登录**按键,点击登录.
3. 返回登录成功后的cookies,
4. 关闭驱动浏览器.

遇到的问题:

  • 开始定位登录框总是失败. 程序报错
    • ==selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {“method”:“id”,“selector”:“username”} ==
    • 找不到 定位元素
  • 原因:
    • 登录框在 一个iframe中,需要切换到包含登录块的frame中
  • 解决方法:

python3 selenium 登录douban,获取cookie

# coding:utf-8
from selenium import webdriver
import time

class doubanLogin():
    def __init__(self):
        self.url = "https://www.douban.com"
        self.driver = webdriver.Chrome(r"***")	#你的google浏览器驱动存放路径

    def login(self):
        self.driver.get(self.url)
        time.sleep(2)                   # 等待浏览器加载 2 秒
        # 切换到子框架
        self.driver.switch_to_frame(self.driver.find_element_by_tag_name('iframe'))
        # 切换登录方式
        self.driver.find_element_by_xpath("/html/body/div[1]/div[1]/ul[1]/li[2]").click()
        username = self.driver.find_element_by_id("username").send_keys("***")
        password = self.driver.find_element_by_id("password").send_keys('***')
        self.driver.find_element_by_class_name('account-form-field-submit').click()
        # time.sleep(10)
    @property
    def get_cookies(self):
        cookies = self.driver.get_cookies()
        return cookies

    def __del__(self):
        self.driver.close()


if __name__ == "__main__":
    douban = doubanLogin()
    douban.login()
    print(douban.get_cookies)