原文地址:http://blog.kantli.com/article/44
進(jìn)行網(wǎng)頁登錄時(shí),經(jīng)常會(huì)碰到登錄過程中出現(xiàn)好幾次跳轉(zhuǎn)的問題。
一般情況下,python3中的urllib.request會(huì)對(duì)重定向進(jìn)行自動(dòng)處理,但有些網(wǎng)站會(huì)在跳轉(zhuǎn)過程中持續(xù)更換cookie,而urllib.request在自動(dòng)處理重定向時(shí)不會(huì)更新cookie,于是有登錄不成功的問題,或者說,跳轉(zhuǎn)過程中因?yàn)閏ookie不對(duì),又回到了登錄界面。
這個(gè)問題簡(jiǎn)單粗暴處理就可以了,重寫request中的重定向處理:
class NoRedirection(urllib.request.HTTPRedirectHandler):
'''
這個(gè)類用于處理重定向問題,原生重定向處理不會(huì)更新cookies,于是干脆不重定向,每次單獨(dú)處理;
'''
def http_error_302(req, fp, code, msg, hdrs, newurl):
return [req, fp, code, msg, hdrs, newurl]
然后在構(gòu)建urlopener的時(shí)候,添加重定向處理參數(shù):
cj = http.cookiejar.LWPCookieJar('Cookie.txt')
ndh = NoRedirection()
ndhOpener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj), https_handler, ndh)
這樣,就可以在登錄發(fā)生重定向時(shí)根據(jù)具體情況進(jìn)行處理,比如說更新cookie并重新訪問:
request = urllib.request.Request(loginUrl, postData, headers)
response = ndhOpener.open(request)
if response[3] == 302:
redirectUrl = response[2].headers['Location']
request = urllib.request.Request(redirectUrl, postData, headers)
cj.load('tmsCookie.txt', ignore_discard=True, ignore_expires=True)
response = ndhOpener.open(request)
cj.save(ignore_discard=True, ignore_expires=True)
如果有多次重定向,只要進(jìn)行多次處理就行了。當(dāng)然,為了減少重復(fù)代碼,也可以把更新cookie的邏輯直接寫到重定向處理類中,但少了一些靈活性,并不一定總是合適。