Python 3.2 – cookielib

Question:

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
Asked By: Stan

||

Answers:

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?

Answered By: Dmitry B.

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
Answered By: Andy Hayden

In Python 3.2, urllib2 is renamed urllib.request, and cookielib is renamed http.cookiejar. So you rename it as urllib.request and http.cookijar

Answered By: Alex Fang

One line answer, that will solve your problem.

import http.cookiejar as cookielib

For python3.
No need to change the occurrence of cookielib in your code.

Answered By: Bhavin Jawade
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.