problem with if then

Jean Dubois jeandubois314 at gmail.com
Mon Jun 10 03:46:13 EDT 2013


On 9 jun, 23:35, Roy Smith <r... at panix.com> wrote:
> In article
> <20165c85-4cc3-4b79-943b-82443e4a9... at w7g2000vbw.googlegroups.com>,
>  Jean Dubois <jeandubois... 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 athttp://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"

thanks a lot, this works like a charm

jean



More information about the Python-list mailing list