一、模拟登录jerry的QQ空间
使用一个第三方登录的链接:https://xui./cgi-bin/xlogin?proxy_url=https%3A///qzone/v6/portal/proxy.html&daid=5&&hide_title_bar=1&low_login=0&qlogin_auto_login=1&no_verifyimg=1&link_target=blank&appid=549000912&style=22&target=self&s_url=https%3A%2F%2Fqzs.%2Fqzone%2Fv5%2Floginsucc.html%3Fpara%3Dizone&pt_qr_app=手机QQ空间&pt_qr_link=http%3A///download.html&self_regurl=https%3A///qzone/v6/reg/index.html&pt_qr_help_link=http%3A///download.html&pt_no_auth=0
也就是说点击下图中的jerry头像就可以登录了。
from selenium import webdriverimport requestsimport timedriver = webdriver.Chrome(r'C:\Users\Administrator\Desktop\chromedriver_win32\chromedriver.exe')#加载第三方的登录方式driver.get('https://xui./cgi-bin/xlogin?proxy_url=https%3A///qzone/v6/portal/proxy.html&daid=5&&hide_title_bar=1&low_login=0&qlogin_auto_login=1&no_verifyimg=1&link_target=blank&appid=549000912&style=22&target=self&s_url=https%3A%2F%2Fqzs.%2Fqzone%2Fv5%2Floginsucc.html%3Fpara%3Dizone&pt_qr_app=手机QQ空间&pt_qr_link=http%3A///download.html&self_regurl=https%3A///qzone/v6/reg/index.html&pt_qr_help_link=http%3A///download.html&pt_no_auth=0')time.sleep(1)button = driver.find_element_by_class_name('face').click()#点击登录time.sleep(2)listCookies = driver.get_cookies() # 获取cookie数据,返回的是python中的list # 解析cookie数据 列表推导式 [] 返回的结果是一个新的列表cookie = [item['name'] + '=' + item['value'] for item in listCookies]cookie_str = '; '.join(item for item in cookie)# 测试代码 selenium获取和解析之后的cookie是否可以使用url = 'https://user./192149641' # 目标url,也就是Jerry老师的QQ空间首页headers = {'cookie':cookie_str,'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'}html = requests.get(url,headers=headers)time.sleep(2)with open('qzong.html','w',encoding='utf-8') as file_obj:file_obj.write(html.text)#打开这个qzong.html是Jerry老师的,那就是成功了。#print(html.text)该text文件中有账号或者昵称等关键字可以证明是Jerry老师的,那就是成功了。
二、怎样保存cookie
json.loads():把json类型的字符串(str)转换成python的数据类型
json.dumps():把python的数据类型转换成json类型的字符串(str)
from selenium import webdriverimport jsondriver = webdriver.Chrome(r'C:\Users\Administrator\Desktop\chromedriver_win32\chromedriver.exe')driver.get('/')# 获取百度的cookielistCookies = driver.get_cookies() # 返回的是python中的list#保存cookiejsonCookies = json.dumps(listCookies) # print(type(jsonCookies),jsonCookies)with open('qqzone.json','w') as file_obj:file_obj.write(jsonCookies)
结果:qqzone.json在sublime中打开