码迷,mamicode.com
首页 > 其他好文 > 详细

跳过cookies访问

时间:2020-01-15 11:28:09      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:rom   信息   adl   _id   word   read   ***   info   click   

from selenium import webdriver
import time,os,json


driver = webdriver.Chrome()
driver.maximize_window()
url = "https://www.cnblogs.com/"
driver.get(url)

#保存cookies到文件中
def save_cookies(driver):
project_path = os.path.dirname(os.getcwd())
file_path = project_path +"/cookies"
if not os.path.exists(file_path):
os.mkdir(file_path)

#从driver中获取cookies
cookies = driver.get_cookies()

#读取cookies
with open(file_path + "Cnblogs.cookies",‘w‘) as c:
json.dump(cookies,c)
print(cookies)

def login():
try:
#登录按钮
driver.find_element_by_xpath(‘//*[@id="span_userinfo"]/a[1]‘).click()
time.sleep(1)
driver.find_element_by_id("LoginName").send_keys(‘wenjing2019‘)
time.sleep(1)
driver.find_element_by_id(‘Password‘).send_keys(‘*****‘)
time.sleep(1)
driver.find_element_by_id(‘submitBtn‘).click()

# 保存cookies到文件中
save_cookies(driver)
finally:
time.sleep(2)


def get_url_with_cookies():
#个人中心界面https://home.cnblogs.com/u/wenjing2019/来验证是否cookies成功
#获取cookies文件并读取
project_path = os.path.dirname(os.getcwd())
file_path = project_path + "/cookies"
cookies_file = file_path + "Cnblogs.cookies"

cn_cookies_file = open(cookies_file,"r")
cn_cookies_file_str = cn_cookies_file.readline()

#加载cookies信息
cn_cookies_file_dict = json.loads(cn_cookies_file_str)

#这个地方先访问网站,先删除旧的cookies,再把保存的cookies添加进去
driver.get("https://www.cnblogs.com/")
driver.delete_all_cookies()

#将cookies信息添加到driver中
for cookies in cn_cookies_file_dict:
driver.add_cookie(cookies)

#验证是否成功
driver.get("https://home.cnblogs.com/u/wenjing2019/")


if __name__=="__main__":
login()
get_url_with_cookies()

跳过cookies访问

标签:rom   信息   adl   _id   word   read   ***   info   click   

原文地址:https://www.cnblogs.com/wenjing2019/p/12195746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!