python3實現讀取chrome瀏覽器cookie,python3chrome

來源:互聯網
上載者:User

python3實現讀取chrome瀏覽器cookie,python3chrome

好幾年前我在做一些自動化的指令碼時,腦子裡也閃過這樣的想法:能不能直接把瀏覽器的cookies取出來用呢?

直到昨天看到代碼《python類比發送動彈》,想起來當年我也曾經有類似的想法沒能完成,那就優先拿這個練手,之後的代碼也會用這個功能。

直接從瀏覽器中取出cookies,有以下好處和用途:

1、不需要配置使用者密碼,直接讀出瀏覽器中cookies就得到一樣的身份,用來完成各種自動化操作。

2、部分網站登入會更新Session,會導致之前成功登入的Session失效,與瀏覽器使用相同的Session,不用進行登入操作,不會互相擠下線。

3、全是廢話,我不想寫了,行嗎?

使用到軟體的sqlite3的圖形管理工具有:

SQLiteDatabaseBrowserPortable http://www.bkjia.com/database/251740.html

sqlitespy http://www.bkjia.com/database/18390.html

使用到的python庫有:

sqlite3 python標準庫,不需要下載安裝

pywin32 pywin32 windows的API庫,讓python可以調用各種各樣的windows API,代碼中用到的win32crypt就是屬於pywin32庫的一部分。 建議手動下載對應版本pywin32安裝 http://www.bkjia.com/softs/416136.html http://www.bkjia.com/softs/416131.html

requests requests是一個相對比較簡單易用的http庫,用來代替urllib23之類的標準庫,使用命令安裝pip install requests

看代碼:

import osimport sqlite3import requestsfrom win32.win32crypt import CryptUnprotectDatadef 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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.