Python模拟登录与cookie保持

模拟登录(selenium & requests & pickle)

  • 使用selenium打开chrome
  • 打开网页

  • 设置时间延迟

  • 手动登录(解决验证码的问题)

  • 获得cookies:传入requests直接使用 / pickle保存至本地

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import selenium
from selenium import webdriver
import time
import pickle

wd = webdriver.Chrome()
wd.get("https://www.zhihu.com")

time.sleep(45)
# 设置时间延迟给手动填写帐号密码及验证码

cookies = wd.get_cookies()

pickle.dump(cookies, open("cookies.pkl", "wb"))     # pickle save cookies
cookies = pickle.load(open("cookies.pkl", "rb"))    # pickle load cookies

s = requests.Session()
for cookie in cookies:
    s.cookies.set(cookie['name'], cookie['value'])

s.headers.clear()
# 删除原始session中标记有python机器人的信息(被网站捕捉到可能造成登录爬取失败)

test = s.get("https://www.zhihu.com")
print test.text


你可能感兴趣的:(Python模拟登录与cookie保持)