python+selenium自動化實戰攜帶cookies模擬登陸微博
阿新 • • 發佈:2021-01-21
首先獲取cookies,使用手機掃碼登入鬥魚,然後利用網頁cookies儲存在本地
有些同學可能會問,這不是相當於自己登入了嗎,還模擬什麼呢,其實來說這是一次獲取cookies可以使用很久
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/12/29 16:27 # @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://weibo.com/login.php') sleep(6) # driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="anony-reg-new"]/div/div[1]/iframe')) # 切換瀏覽器標籤定位的作用域 driver.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[1]/div/a[2]').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儲存成功!')
然後利用cookies登入到微博,實現模擬登陸
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/12/29 16:30 # @Author : huni # @File : 攜帶cookies模擬登陸微博.py # @Software: PyCharm from selenium import webdriver from selenium.webdriver.chrome.options import Options from time import sleep 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://weibo.com/login.php') 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': '.weibo.com','name': cookie.get('name'),'value': cookie.get('value'),"expires": '','path': '/','httpOnly': False,'HostOnly': False,'Secure': False } browser.add_cookie(cookie_dict) sleep(3) browser.refresh() # 重新整理網頁,cookies才成功 if __name__ == "__main__": browser = browser_initial() log_csdn(browser)
到此這篇關於python+selenium自動化實戰攜帶cookies模擬登陸微博的文章就介紹到這了,更多相關selenium自動化cookies模擬登陸內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!