ly0 / baidupcsapi

百度网盘api
MIT License
1.21k stars 234 forks source link

如何手動匯入cookie? #51

Closed abccbaandy closed 7 years ago

abccbaandy commented 7 years ago

目前登入一直跳 baidupcsapi.api.LoginFailed: 登录失败,请在弹出的窗口操作,或重新登录,但網頁版正常,所以我想把cookie從chrome導出到file,然後試著修改 _load_cookies

def _load_cookies(self):
        cookies_file = '.{0}.cookies'.format(self.username)
        logging.debug('cookies file:' + cookies_file)
        if os.path.exists(cookies_file):
            logging.debug('%s cookies file has already existed.' %
                          self.username)
            with open(cookies_file, 'r') as cookies_file:
                # cookies = requests.utils.cookiejar_from_dict(
                #         pickle.load(cookies_file))
                # logging.debug(str(cookies))
                cookies = {}
                cookie_json = json.load(cookies_file)
                for cookie in cookie_json:
                    cookies[cookie['name']] = cookie['value']
                self.session.cookies = cookies
                self.user['BDUSS'] = self.session.cookies['BDUSS']
                # print(self.session.cookies)
                return True
        else:
            return False

不過執行會出現

  File "baidu\api.py", line 497, in __init__
    verify_func=verify_callback)
  File "baidu\api.py", line 169, in __init__
    self._initiate()
  File "baidu\api.py", line 230, in _initiate
    self.user['token'] = self._get_token()
  File "baidu\api.py", line 263, in _get_token
    time.time()), cookies=self.session.cookies).text.replace('\'', '\"')
  File "C:\Python34\lib\site-packages\requests\sessions.py", line 501, in get
    return self.request('GET', url, **kwargs)
  File "C:\Python34\lib\site-packages\requests\sessions.py", line 488, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python34\lib\site-packages\requests\sessions.py", line 624, in send
    extract_cookies_to_jar(self.cookies, request, r.raw)
  File "C:\Python34\lib\site-packages\requests\cookies.py", line 135, in extract_cookies_to_jar
    jar.extract_cookies(res, req)
AttributeError: 'dict' object has no attribute 'extract_cookies'

請問還有哪邊需要修改呢?

ly0 commented 7 years ago

cookies对象必须是一个Cookiejar对象

abccbaandy commented 7 years ago

我看了下 _save_cookies,發現 dict_from_cookiejar 其實只是把 cookiejar 轉成 hashmap ,格式剛好就是我上面的 cookies ,於是自己寫了個 converter 搭配 pickle.dump 轉成 .XXXX.cookies 就搞定了XD

附上code給有同樣需求的人,.test.cookies 改成自己的名字就OK了

import json
import pickle

# noinspection SpellCheckingInspection
def save_cookies(cookies):
    cookies_file = '.test.cookies'
    with open(cookies_file, 'wb') as f:
        pickle.dump(cookies, f)

def load_cookies():
    cookies = {}
    with open('export.json', 'r') as cookies_file:
        cookie_json = json.load(cookies_file)
        for cookie in cookie_json:
            cookies[cookie['name']] = cookie['value']
    return cookies

save_cookies(load_cookies())
HaoweiCh commented 7 years ago

有库可以直接读chrome或者firefox的用户cookie