Python-Ref > Accessing the Internet > Downloading things > Checking if a page is available
 
 

^^->

Checking if a page is available

The simplest way to check if a page is available is to try to open it and see if an error occurs.
Expand/Shrink
Zdroj: (download1-1.py)
  1   import urllib2   # library for accessing the web
  2   
  3   url = "http://slashdot.org"
  4   try:
  5       f = urllib2.urlopen( url)      # try to open the URL for reading
  6   except urllib2.URLError:           # if an error occurs...
  7       print "page is not available"  # ...the page is not available
  8   else:
  9       f.close()                      # otherwise close it
 10       print "page %s opened" % url
stdout:
page http://slashdot.org opened
Doba běhu: 646.5 ms
Expand/Shrink
Zdroj: (download1-2.py)
  1   import urllib2   # library for accessing the web
  2   
  3   def checkURL( url):
  4       try:
  5           f = urllib2.urlopen( url)   # try to open the URL for reading
  6       except urllib2.URLError:        # if an error occurs...
  7           return False                # ...the page is not available
  8       f.close()                       # otherwise close it
  9       return True                     # and return True
 10   
 11   
 12   print checkURL( "http://slashdot.org")
 13   print checkURL( "http://something-not-very-probable-but-who-knows.com")
stdout:
True
False
Doba běhu: 536.1 ms