Python用selenium获取cookie以后给rqeuests使用。

先使用selenium的get_cookies()方法获取cookie,再使用 requests.Session() 使用cookie

获取

  • 首先用selenium自带的get_cookies()方法获取cookie

代码如下:

  • 我用的Chrome,扫码登录百度贴吧
from selenium import webdriver
import time
import requests
import json
import os

class TieBa:
    def __init__(self):
        pass

    def main_html(self): # 启动网页扫码登录获取cookie
        self.driver = webdriver.Chrome()
        self.url = 'https://www.baidu.com'
        self.driver.get(self.url)
        self.driver.find_element_by_xpath('//*[@id="s-top-left"]/a[6]').click()
        self.driver.switch_to.window(self.driver.window_handles[1])
        self.driver.find_element_by_xpath('//*[@id="com_userbar"]/ul/li[4]/div/a').click()  # 扫码登录
        time.sleep(10)

    def get_cookie(self):
        time.sleep(3)
        try:
            dict_cookie = self.driver.get_cookies()
            json_cookie = json.dumps(dict_cookie)
            with open("TieBaCookies3.txt", 'w+') as f:
                f.write(json_cookie)
            print("保存成功")
        except:
            print("保存失败")

使用(Session.cookies.set(cookie[‘name’],cookie[‘value’]))

    def get_html(self):
        se = requests.Session()
        with open("TieBaCookies3.txt", 'r', encoding='UTF-8') as f:
            listCookies = json.loads(f.read())
            for cookie in listCookies:
                se.cookies.set(cookie['name'], cookie['value'])
            url = 'http://www.tieba.com'
            html = se.post(url)
            print(html.text)  # 可以看到用户名变为你自己了。即为成功。

if __name__ == '__main__':
    tieba = TieBa()
    if not os.path.exists('TieBaCookies3.txt'):
        tieba.main_html()
        tieba.get_cookie()
        tieba.get_html()
    else:
        tieba.get_html()

结果:

在这里插入图片描述在这里插入图片描述

  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值