~ubuntu-branches/ubuntu/lucid/python2.6/lucid

« back to all changes in this revision

Viewing changes to Doc/howto/urllib2.rst

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-04-08 02:29:05 UTC
  • mto: (10.1.3 experimental)
  • mto: This revision was merged to the branch mainline in revision 23.
  • Revision ID: james.westby@ubuntu.com-20090408022905-xa5zbe8821m2o77o
Tags: upstream-2.6.2~rc1
ImportĀ upstreamĀ versionĀ 2.6.2~rc1

Show diffs side-by-side

added added

removed removed

Lines of Context:
10
10
    HOWTO, available at `urllib2 - Le Manuel manquant
11
11
    <http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml>`_.
12
12
 
13
 
 
 
13
 
14
14
 
15
15
Introduction
16
16
============
19
19
 
20
20
    You may also find useful the following article on fetching web resources
21
21
    with Python :
22
 
    
 
22
 
23
23
    * `Basic Authentication <http://www.voidspace.org.uk/python/articles/authentication.shtml>`_
24
 
    
 
24
 
25
25
        A tutorial on *Basic Authentication*, with examples in Python.
26
26
 
27
27
**urllib2** is a `Python <http://www.python.org>`_ module for fetching URLs
98
98
*not* from ``urllib2``. ::
99
99
 
100
100
    import urllib
101
 
    import urllib2  
 
101
    import urllib2
102
102
 
103
103
    url = 'http://www.someserver.com/cgi-bin/register.cgi'
104
104
    values = {'name' : 'Michael Foord',
161
161
Explorer [#]_. ::
162
162
 
163
163
    import urllib
164
 
    import urllib2  
165
 
    
 
164
    import urllib2
 
165
 
166
166
    url = 'http://www.someserver.com/cgi-bin/register.cgi'
167
 
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' 
 
167
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
168
168
    values = {'name' : 'Michael Foord',
169
169
              'location' : 'Northampton',
170
170
              'language' : 'Python' }
171
171
    headers = { 'User-Agent' : user_agent }
172
 
    
 
172
 
173
173
    data = urllib.urlencode(values)
174
174
    req = urllib2.Request(url, data, headers)
175
175
    response = urllib2.urlopen(req)
183
183
===================
184
184
 
185
185
*urlopen* raises :exc:`URLError` when it cannot handle a response (though as usual
186
 
with Python APIs, builtin exceptions such as 
 
186
with Python APIs, builtin exceptions such as
187
187
:exc:`ValueError`, :exc:`TypeError` etc. may also
188
188
be raised).
189
189
 
309
309
geturl, and info, methods. ::
310
310
 
311
311
    >>> req = urllib2.Request('http://www.python.org/fish.html')
312
 
    >>> try: 
 
312
    >>> try:
313
313
    >>>     urllib2.urlopen(req)
314
314
    >>> except URLError, e:
315
315
    >>>     print e.code
316
316
    >>>     print e.read()
317
 
    >>> 
 
317
    >>>
318
318
    404
319
 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
 
319
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
320
320
        "http://www.w3.org/TR/html4/loose.dtd">
321
 
    <?xml-stylesheet href="./css/ht2html.css" 
 
321
    <?xml-stylesheet href="./css/ht2html.css"
322
322
        type="text/css"?>
323
 
    <html><head><title>Error 404: File Not Found</title> 
 
323
    <html><head><title>Error 404: File Not Found</title>
324
324
    ...... etc...
325
325
 
326
326
Wrapping it Up
372
372
            print 'Error code: ', e.code
373
373
    else:
374
374
        # everything is fine
375
 
        
 
375
 
376
376
 
377
377
info and geturl
378
378
===============
443
443
and a 'realm'. The header looks like : ``Www-authenticate: SCHEME
444
444
realm="REALM"``.
445
445
 
446
 
e.g. :: 
 
446
e.g. ::
447
447
 
448
448
    Www-authenticate: Basic realm="cPanel Users"
449
449
 
467
467
than the URL you pass to .add_password() will also match. ::
468
468
 
469
469
    # create a password manager
470
 
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()                        
 
470
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
471
471
 
472
472
    # Add the username and password.
473
 
    # If we knew the realm, we could use it instead of ``None``.
 
473
    # If we knew the realm, we could use it instead of None.
474
474
    top_level_url = "http://example.com/foo/"
475
475
    password_mgr.add_password(None, top_level_url, username, password)
476
476
 
477
 
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)                            
 
477
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
478
478
 
479
479
    # create "opener" (OpenerDirector instance)
480
 
    opener = urllib2.build_opener(handler)                       
 
480
    opener = urllib2.build_opener(handler)
481
481
 
482
482
    # use the opener to fetch a URL
483
 
    opener.open(a_url)      
 
483
    opener.open(a_url)
484
484
 
485
485
    # Install the opener.
486
486
    # Now all calls to urllib2.urlopen use our opener.
487
 
    urllib2.install_opener(opener)                               
 
487
    urllib2.install_opener(opener)
488
488
 
489
489
.. note::
490
490
 
540
540
 
541
541
    # timeout in seconds
542
542
    timeout = 10
543
 
    socket.setdefaulttimeout(timeout) 
 
543
    socket.setdefaulttimeout(timeout)
544
544
 
545
545
    # this call to urllib2.urlopen now uses the default timeout
546
546
    # we have set in the socket module
557
557
This document was reviewed and revised by John Lee.
558
558
 
559
559
.. [#] For an introduction to the CGI protocol see
560
 
       `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_. 
 
560
       `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_.
561
561
.. [#] Like Google for example. The *proper* way to use google from a program
562
562
       is to use `PyGoogle <http://pygoogle.sourceforge.net>`_ of course. See
563
563
       `Voidspace Google <http://www.voidspace.org.uk/python/recipebook.shtml#google>`_
574
574
       is set to use the proxy, which urllib2 picks up on. In order to test
575
575
       scripts with a localhost server, I have to prevent urllib2 from using
576
576
       the proxy.
577
 
.. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe 
 
577
.. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe
578
578
       <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456195>`_.
579
 
 
 
579