首先是获取cookies保存到本地
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/20 11:00
# @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://passport.csdn.net/login?code=public' )
sleep( 2 )
driver.find_element_by_xpath( '/html/body/div[2]/div/div/div[1]/div[2]/div[5]/ul/li[1]/a' ).click()
sleep( 6 )
dictCookies = driver.get_cookies() # 获取list的cookies
jsonCookies = json.dumps(dictCookies) # 转换成字符串保存
with open ( 'csdn_cookies.txt' , 'w' ) as f:
f.write(jsonCookies)
print ( 'cookies保存成功!' )
|
然后是利用本地的cookies模拟登陆csdn首页
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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/20 11:10
# @Author : huni
# @File : 使用cookies登录csdn.py
# @Software: PyCharm
from selenium import webdriver
import json
def browser_initial():
browser = webdriver.Chrome(executable_path = './chromedriver.exe' )
browser.maximize_window()
browser.get(
'https://www.csdn.net/' )
return browser
def log_csdn(browser):
with open ( 'csdn_cookies.txt' , 'r' , encoding = 'utf8' ) as f:
listCookies = json.loads(f.read())
# 往browser里添加cookies
for cookie in listCookies:
cookie_dict = {
'domain' : '.csdn.net' ,
'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)
|
cookies是有时间限制的,定期获取即可,登陆之后可以进行其他自动化操作,比如给别人的博客评论,点赞等等。
到此这篇关于selenium携带cookies模拟登陆CSDN的实现的文章就介绍到这了,更多相关selenium cookies模拟登陆内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/m0_50944918/article/details/111415040