38

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
Stan
  • 25,744
  • 53
  • 164
  • 242

4 Answers4

47

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?

Dmitry B.
  • 9,107
  • 3
  • 43
  • 64
21

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
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
18

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.

Bhavin Jawade
  • 331
  • 2
  • 5
6

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

Alex Fang
  • 95
  • 1
  • 2