import urllib.request import urllib.parse import urllib.error import http.cookiejar url='http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=La2A2' data={ 'username':'zhanghao', 'password':'mima', } postdata=urllib.parse.urlencode(data).encode('utf8') header={ 'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } request=urllib.request.Request(url,postdata,headers=header) #使用http.cookiejar.CookieJar()創建CookieJar對象 cjar=http.cookiejar.CookieJar() #使用HTTPCookieProcessor創建cookie處理器,並以其為參數構建opener對象 cookie=urllib.request.HTTPCookieProcessor(cjar) opener=urllib.request.build_opener(cookie) #將opener安裝為全局 urllib.request.install_opener(opener) try: reponse=urllib.request.urlopen(request) except urllib.error.HTTPError as e: print(e.code) print(e.reason) fhandle=open('./test1.html','wb') fhandle.write(reponse.read()) fhandle.close() url2='http://bbs.chinaunix.net/forum-327-1.html' #打開test2.html文件,會發現此時會保持我們的登錄信息,為已登錄狀態。也就是說,對應的登錄狀態已經通過Cookie保存。 reponse2=urllib.request.urlopen(url) fhandle2=open('./test2.html','wb') fhandle2.write(reponse2.read()) fhandle2.close()
轉自:https://blog.csdn.net/duxu24/article/details/77414298?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control