odbhut.shei.chhele
odbhut.shei.chhele

Reputation: 6244

How can I use urllib.request in Python 2?

When I try to use this code in Python 2.7.4:

import urllib.request

class App():
    def main(self):
        inp = raw_input('Please enter a string\n')
        print(inp)
        inp = input('Please enter a value\n')
        print(inp)

if __name__ == '__main__':
    App().main()

I get an error that says 'no import named request'. If I instead write import urllib, then I don't get any import error, but I can't use the functionality.

Upvotes: -1

Views: 1796

Answers (2)

Hyperboreus
Hyperboreus

Reputation: 32429

Here is a simple sandbox implementation for python2.7:

import urllib

def main():
    #one indentation level
    print urllib.urlopen("http://stackoverflow.com").read ()

if __name__ == '__main__': main()

If this code runs and yours doesn't, then the problem is not with importing/using urllib. It runs on my machine using pthon2.7.4.

Alternative version:

from urllib import urlopen

def main():
    #one indentation level
    print urlopen("http://stackoverflow.com").read ()

if __name__ == '__main__': main()

Or using your App-Class:

import urllib

class App:
    def main(self):
        print urllib.urlopen("http://stackoverflow.com").read ()

if __name__ == '__main__':
    App().main()

Upvotes: 1

TerryA
TerryA

Reputation: 59974

urllib.request is for Python 3. For Python 2, you'll want to do:

from urllib import urlopen

Or use the urllib2 module:

from urllib2 import urlopen

You shouldn't be getting an IndentationError, but you may have done some minor error.

Upvotes: 1

Related Questions