(编辑:jimmy 日期: 2024/12/28 浏览:2)
首先获取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)