首先获取cookies,使用手机扫码登录斗鱼,然后利用网页cookies保存在本地
有些同学可能会问,这不是相当于自己登录了吗,还模拟什么呢,其实来说这是一次获取cookies可以使用很久
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/29 10:58
# @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.douyu.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('//*[@id="js-header"]/div/div/div[3]/div[7]/div/div/a/span').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 11:01
# @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.douyu.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': '.douyu.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叭
打赏小编点这里哦