problem with if then
Roy Smith
roy at panix.com
Sun Jun 9 17:35:20 EDT 2013
In article
<20165c85-4cc3-4b79-943b-82443e4a9bd0 at w7g2000vbw.googlegroups.com>,
Jean Dubois <jeandubois314 at gmail.com> wrote:
> But, really,
> > once you've done all that (and it's worth doing as an exercise), rewrite
> > your code to use urllib2 or requests. It'll be a lot easier.
>
> Could you show me how to code the example in metacode below wuth the
> use of urllib2?
> #!/usr/bin/env python
> import urllib2
> if check whether url exists succeed:
> print 'url exists'
> else:
> print 'url does not exist'
There are two basic ways Python function return status information.
Either they return something which indicates failure (such as None), or
they raise an exception.
In this case, what you want is urlopen(), which is documented at
http://docs.python.org/2/library/urllib2.html. The key piece of
information is a couple of paragraphs down, where it says, "Raises
URLError on errors".
It's not obvious from reading that whether URLError is a built-in or
not, but that's easy enough to figure out:
>>> URLError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'URLError' is not defined
>>> import urllib2
>>> urllib2.URLError
<class 'urllib2.URLError'>
So, that means you want something like:
#!/usr/bin/env python
import urllib2
url = "http://whatever...."
try:
urllib2.urlopen(url)
print "url exists"
except urllib2.URLError:
print "url does not exist"
More information about the Python-list
mailing list