87

I am using Windows, and I get the error:

ImportError: No module named urllib2

I think this is the solution for Linux. But how to set this in Windows?

I am using Python 3.2 and I am not able see urllib2 there in the LiB folder.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Varada
  • 871
  • 1
  • 6
  • 4

3 Answers3

147

In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.

To make Python 2 code work in Python 3:

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2
Community
  • 1
  • 1
newbie
  • 2,412
  • 5
  • 22
  • 26
  • Could you be so kind to explain how to solve the problem? From the link I see that some changes were made in the package, but what with should I replace `urllib2` in the the python command to succeed installation? Replacing `urllib2` with `urllib.request` doesn't help. – Green Jul 17 '13 at 20:14
  • Note that you also need to add decode() to your line reader, ie change from row = line.strip().split(",") to row = line.decode().strip().split(",") – ski_squaw Apr 19 '16 at 08:53
24

PYTHON 3

import urllib.request

wp = urllib.request.urlopen("http://example.com")

pw = wp.read()

print(pw)

PYTHON 2

import urllib

 import sys

 wp = urllib.urlopen("http://example.com")

 for line in wp:

     sys.stdout.write(line)

While I have tested both the Codes in respective versions.

anthonyvd
  • 7,329
  • 4
  • 30
  • 51
Shivam Kotwalia
  • 1,419
  • 2
  • 15
  • 20
5
    import urllib2

Traceback (most recent call last):

File "", line 1, in

    import urllib2

ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.

Here is the PEP link (Python Enhancement Proposals )

http://www.python.org/dev/peps/pep-3108/#urllib-package

so instead of urllib2 you can now import urllib.request and then use it like this:

    >>>import urllib.request

    >>>urllib.request.urlopen('http://www.placementyogi.com')

Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x

user2649102
  • 181
  • 3
  • 9