urllib and sites that require passwds

Fuzzyman fuzzyman at gmail.com
Thu Dec 23 09:38:09 EST 2004


USe urllib2 which will fail with an exception. You can trap this
exception and using the code attribute of the exception object,
determine why it failed. The error code for 'authentication required'
is 401.

Off the top of my head :

import urllib2
req = urllib2.Request(theurl)
try:
handle = urllib2.urlopen(req)
except IOError, e:
if not e.hasattr('code'):
print 'The url appears to be invalid.'
print e.reason
else:
if e.code == 401:
print theurl, 'is protected with a password.'
else:
print 'We failed with error code', e.code
HTH

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml




More information about the Python-list mailing list