2016-03-02 20 views
0

所以我有一個工作代碼,從網站獲取數據,連接到它,如果有必要,並保存在一個文件中,以便他們堅持每次啓動代碼時。下面的代碼是什麼樣子(我明明已經刪除了進口,大部分代碼,以使其更易於閱讀)請求和文件cookiejar不工作在一個類

cookiejar_file = 'tmp/cookies.txt' 

cj = http.cookiejar.LWPCookieJar(cookiejar_file) 
try: 
    cj.load(ignore_discard=True) 
except: 
    pass 

s = requests.Session() 
s.cookies = cj 

# Do stuff, connect if necessary by doing a s.post() on the connect page 

cj.save(cookiejar_file, ignore_discard=True) 

但現在,我想創造一個更清潔類做這個工作有一個問題:每次運行代碼時,都必須重新連接到網站。所以我一定是做錯了,餅乾沒有成功加載我猜?

class Parent: 

    CookieFile = 'tmp/cookies.txt' 

    def __init__(self): 
     self.cj = http.cookiejar.LWPCookieJar(Parent.CookieFile) 
     self.cj.load() 
     self.session = requests.Session() 
     self.session.cookies = self.cj 

    def save_cookies(self): 
     self.cj.save(Parent.CookieFile, ignore_discard=True) 


class Child(Parent): 

    def __init__(self): 
     Parent.__init__(self) 

    def main(self): 
     # Do stuff, connect if necessary 
     self.save_cookies() 

a = Child 
a.main() 

是否有與我這樣做的方式有問題?對我來說,它看起來應該是做同樣的事情。 在我第一次執行代碼時,cookie文件已經成功創建,並且每次執行時都會更改cookie。

+0

爲什麼不self.CookieFile代替Parent.CookieFile的?你應該通過這樣做來創建一個Child類的實例a = Child() – tinySandy

+0

Parent.CookieFile可以工作,所以這不是問題。代碼也可以工作,我在這裏簡化了它,因此它更具可讀性並且忘記了括號。 – Symael

回答

0

那麼問題就在於我在加載Cookiejar時忘記了「ignore_discard = True」。

這工作完全使用Python 3.5.1和2.9.1請求:

import requests 
import http.cookiejar 


class Parent: 

    CookieFile = 'tmp/cookies.txt' 

    def __init__(self): 
     self.cj = http.cookiejar.LWPCookieJar(Parent.CookieFile) 
     self.cj.load(ignore_discard=True) 
     self.session = requests.Session() 
     self.session.cookies = self.cj 

    def save_cookies(self): 
     self.cj.save(Parent.CookieFile, ignore_discard=True) 


class Child(Parent): 

    def __init__(self): 
     Parent.__init__(self) 

    def main(self): 
     # Do stuff, connect if necessary 
     self.save_cookies() 

a = Child 
a.main()