python read and validate input url

17,408

Solution 1

If you are trying to implement to code from web2py url validator, you will notice that you have added and indent to the else where none is needed. White space is important in python. The code that was given in my previous answer is correct, you have just copied it incorrectly. Your code should read like this (the same as my previous answer):

from urllib2 import Request, urlopen, URLError

url = raw_input('enter something')
req = Request(url)
try:
    response = urlopen(req)
except URLError, e:
    if hasattr(e, 'reason'):
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'):
        print 'The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code
else:
    print 'URL is good!'

The else clause is part of the try except not part of the exception test. Basically if an exception is not thrown, the url is valid. The following code gives you this result if you enter http://www.google.com

python test.py 
enter somethinghttp://www.google.com
URL is good!

If you enter http://www.google.com/bad you get:

python test.py 
enter somethinghttp://www.google.com/bad
The server couldn't fulfill the request.
Error code:  404

Solution 2

Try entering the full URL in your input:

entersomething http://www.google.com

You need to specify the type of request in order for it to understand handle it properly (in this case, http).

Share:
17,408

Related videos on Youtube

Hojat Taheri
Author by

Hojat Taheri

LPIc 2 linux proffesional Security Researcher Python Programmer :)

Updated on June 04, 2022

Comments

  • Hojat Taheri
    Hojat Taheri almost 2 years

    Possible Duplicate:
    web2py url validator

    would you help me on this code?

    from urllib2 import Request, urlopen, URLError
    
    url = raw_input('enter something')
    req = Request(url)
    try:
        response = urlopen(req)
    except URLError, e:
        if hasattr(e, 'reason'):
            print 'We failed to reach a server.'
            print 'Reason: ', e.reason
        elif hasattr(e, 'code'):
            print 'The server couldn\'t fulfill the request.'
            print 'Error code: ', e.code
        else:
            print 'URL is good!'
    
    • Inbar Rose
      Inbar Rose over 11 years
      please edit your post and format it for readability - what have you tried? what exactly is your question?
    • Hojat Taheri
      Hojat Taheri over 11 years
      i want to ask user to enter an url then validate it..
    • Hojat Taheri
      Hojat Taheri over 11 years
      Traceback (most recent call last): File "C:/Users/r00t-7/PycharmProjects/untitled/sample.py", line 7, in <module> response = urlopen(req) File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 366, in open protocol = req.get_type() File "C:\Python25\lib\urllib2.py", line 241, in get_type raise ValueError, "unknown url type: %s" % self.__original ValueError: unknown url type: www.google.com Process finished with exit code 1
    • Admin
      Admin over 11 years
      I think your else clause needs to be un-indented. Now it will only print "Url is good!" when there is an URLError.
  • Hojat Taheri
    Hojat Taheri over 11 years
    well, i tried to check the protocol in this way, any better idea? if url[0:7] == 'http://' or url[0:8] == 'https://' or url[0:6] =='ftp://': [do something with url..]
  • Hojat Taheri
    Hojat Taheri over 11 years
    i know but i want to check it, i want my code be friendly, users just enter it..i do the stuff..
  • Hojat Taheri
    Hojat Taheri over 11 years
    i wrote this in a neat way in python, now i have to use it in web2py, this is my code written with your help, thanks all, if you think that it can be better please comment it, i love u guys.. by the way, because i'm new to stackoverflow i can post my answear 4 hours later..
  • BigHandsome
    BigHandsome over 11 years
    Glad to help. If there is a correct answer to your questions make sure to select it so the person that helped gets rewarded.
  • Hojat Taheri
    Hojat Taheri over 11 years
    sure but the problem is that my reputation is under 15 :)))
  • BigHandsome
    BigHandsome over 11 years
    Your rep does not need to be over 15 to accept an answer, only to upvote a question or an answer. To select and answer see: meta.stackexchange.com/questions/5234/…
  • RocketDonkey
    RocketDonkey over 11 years
    Ah, my mistake - I thought you were asking why the code didn't work. Glad you found your answer!