读取浏览器cookies的python脚本

日常作爬虫调试,遇到小项目,作可行性分析的时候。cookies 的问题每每不是最复杂的,我通常直接调用使用本身的浏览器里面的cookies来作测试 关键请求,简单的请求就不须要取用抓包了。 原理:读取sqlite3的数据。这里我是拿的2345加速浏览器,版本8.8.0.16453
这里我直接获取我已经登入的开源中国帐号作测试。
我用的python2,里面的sqlite3.dll有问题,因此须要替换DLL/里面的sqlite3.dll,才能正常使用。
很久以前的代码了,印象之中好像是支持火狐和谷歌的某些版本,又兴趣的能够自行换文件路径测试下
百度云:https://pan.baidu.com/s/1tpMwPfaQXB88lciWl5v_rghtml

import os
import sqlite3
import requests
import win32crypt
 
def getcookiefromchrome(host='.oschina.net'):
  #cookiepath=os.environ['LOCALAPPDATA']+r"\Google\Chrome\User Data\Default\Cookies"
  cookiepath=os.environ['LOCALAPPDATA']+r"\2345Explorer\User Data\Default\CookiesV3"
  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:win32crypt.CryptUnprotectData(encrypted_value)[1].decode() for host_key,name,encrypted_value in cu.execute(sql).fetchall()}
    return cookies

def test2(cookies):
    url='https://my.oschina.net/u/2367514/admin/profile'
 
    httphead={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',}
    r=requests.get(url,headers=httphead,cookies=cookies,allow_redirects=1,verify=False)
    if 'NLGBZJ' in r.text:
        print('login cookies isok!')
    else:
      print('login cookies is fail')
      #with open('fail_cookies.html','w+') as f:
        #f.write(r.text)
if __name__=='__main__':
    cookies=getcookiefromchrome()
    print cookies
    test2(cookies)
相关文章
相关标签/搜索