首先获取cookies,使用手机扫码登录斗鱼,然后利用网页cookies保存在本地
有些同学可能会问,这不是相当于自己登录了吗,还模拟什么呢,其实来说这是一次获取cookies可以使用很久
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/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登录到微博,实现模拟登陆
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
#!/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模拟登陆内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/m0_50944918/article/details/111930390