Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.2 - cookielib

I have working 2.7 code, however there are no such thing as cookielib and urllib2 in 3.2? How can I make this code work on 3.2? In case someone is wondering - I'm on Windows.

Example 2.7

import urllib, urllib2, cookielib  cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))  login_data = urllib.urlencode({'login' : 'admin', 'pass' : '123'})  resp = opener.open('http://website/', login_data) html = resp.read()  # I know that 3.2 is using print(), don't have to point that out. print html 
like image 371
Stan Avatar asked Dec 06 '11 18:12

Stan


2 Answers

As mentioned above cookielib has been renamed, use the following snippet for both python 2 and 3:

try:     from http.cookiejar import CookieJar except ImportError:     from cookielib import CookieJar 
like image 41
Andy Hayden Avatar answered Sep 27 '22 20:09

Andy Hayden


From Python docs:

Note The cookielib module has been renamed to http.cookiejar in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

Is that not an acceptable solution? If not, why?

like image 71
Dmitry B. Avatar answered Sep 27 '22 19:09

Dmitry B.