python3实现读取chrome浏览器cookie

yipeiwu_com7年前Python基础

好几年前我在做一些自动化的脚本时,脑子里也闪过这样的想法:能不能直接把浏览器的cookies取出来用呢?

直到昨天看到代码《python模拟发送动弹》,想起来当年我也曾经有类似的想法没能完成,那就优先拿这个练手,之后的代码也会用这个功能。

直接从浏览器中取出cookies,有以下好处和用途:

1、不需要配置用户密码,直接读出浏览器中cookies就得到一样的身份,用来完成各种自动化操作。

2、部分网站登录会更新Session,会导致之前成功登录的Session失效,与浏览器使用相同的Session,不用进行登录操作,不会互相挤下线。

3、全是废话,我不想写了,行吗?

使用到软件的sqlite3的图形管理工具有:

SQLiteDatabaseBrowserPortable https://www.jb51.net/database/251740.html

sqlitespy https://www.jb51.net/database/18390.html

使用到的python库有:

sqlite3 python标准库,不需要下载安装

pywin32 pywin32 windows的API库,让python可以调用各种各样的windows API,代码中用到的win32crypt就是属于pywin32库的一部分。 建议手动下载对应版本pywin32安装 https://www.jb51.net/softs/416136.html https://www.jb51.net/softs/416131.html

requests requests是一个相对比较简单易用的http库,用来代替urllib23之类的标准库,使用命令安装pip install requests

看代码:

import os
import sqlite3
import requests
from win32.win32crypt import CryptUnprotectData

def getcookiefromchrome(host='.oschina.net'):
  cookiepath=os.environ['LOCALAPPDATA']+r"\Google\Chrome\User Data\Default\Cookies"
  sql="select host_key,name,encrypted_value from cookies where host_key='%s'" % host
  with sqlite3.connect(cookiepath) as conn:
    cu=conn.cursor()    
    cookies={name:CryptUnprotectData(encrypted_value)[1].decode() for host_key,name,encrypted_value in cu.execute(sql).fetchall()}
    print(cookies)
    return cookies

#运行环境windows 2012 server python3.4 x64 chrome 50
#以下是测试代码
#getcookiefromchrome()
#getcookiefromchrome('.baidu.com')

url='http://my.oschina.net/'

httphead={'User-Agent':'Safari/537.36',}

#设置allow_redirects为真,访问http://my.oschina.net/ 可以跟随跳转到个人空间
r=requests.get(url,headers=httphead,cookies=getcookiefromchrome('.oschina.net'),allow_redirects=1)
print(r.text)

相关文章

django 连接数据库 sqlite的例子

Aphorism the fight is worth it. django models 连接 sqlite 数据库 django 版本为 1.11.7 在 blog 项目下创建一个...

使用python统计文件行数示例分享

复制代码 代码如下:import time def block(file,size=65536):    while True:  &n...

使用python验证代理ip是否可用的实现方法

在使用爬虫爬取网络数据时,如果长时间对一个网站进行抓取时可能会遇到IP被封的情况,这种情况可以使用代理更换ip来突破服务器封IP的限制。 随手在百度上搜索免费代理IP,可以得到一系列的网...

Linux下使用python自动修改本机网关代码分享

#!/usr/bin/python #auto change gateway Created By mickelfeng import os import random,re g='...

PyChar学习教程之自定义文件与代码模板详解

PyChar学习教程之自定义文件与代码模板详解

前言 PyCharm是由JetBrains打造的一款Python IDE。大家都知道,PyCharm提供了文件和代码模板功能,可以利用此模板来快捷新建代码或文件。 比如在PyCharm中...