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中
  • 解決方法:

豆瓣登錄頁面

# 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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章