1.. _urllib-howto: 2 3************************************************ 4 HOWTO Fetch Internet Resources Using urllib2 5************************************************ 6 7:Author: `Michael Foord <http://www.voidspace.org.uk/python/index.shtml>`_ 8 9.. note:: 10 11 There is a French translation of an earlier revision of this 12 HOWTO, available at `urllib2 - Le Manuel manquant 13 <http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml>`_. 14 15 16 17Introduction 18============ 19 20.. sidebar:: Related Articles 21 22 You may also find useful the following article on fetching web resources 23 with Python: 24 25 * `Basic Authentication <http://www.voidspace.org.uk/python/articles/authentication.shtml>`_ 26 27 A tutorial on *Basic Authentication*, with examples in Python. 28 29**urllib2** is a Python module for fetching URLs 30(Uniform Resource Locators). It offers a very simple interface, in the form of 31the *urlopen* function. This is capable of fetching URLs using a variety of 32different protocols. It also offers a slightly more complex interface for 33handling common situations - like basic authentication, cookies, proxies and so 34on. These are provided by objects called handlers and openers. 35 36urllib2 supports fetching URLs for many "URL schemes" (identified by the string 37before the ``":"`` in URL - for example ``"ftp"`` is the URL scheme of 38``"ftp://python.org/"``) using their associated network protocols (e.g. FTP, HTTP). 39This tutorial focuses on the most common case, HTTP. 40 41For straightforward situations *urlopen* is very easy to use. But as soon as you 42encounter errors or non-trivial cases when opening HTTP URLs, you will need some 43understanding of the HyperText Transfer Protocol. The most comprehensive and 44authoritative reference to HTTP is :rfc:`2616`. This is a technical document and 45not intended to be easy to read. This HOWTO aims to illustrate using *urllib2*, 46with enough detail about HTTP to help you through. It is not intended to replace 47the :mod:`urllib2` docs, but is supplementary to them. 48 49 50Fetching URLs 51============= 52 53The simplest way to use urllib2 is as follows:: 54 55 import urllib2 56 response = urllib2.urlopen('http://python.org/') 57 html = response.read() 58 59Many uses of urllib2 will be that simple (note that instead of an 'http:' URL we 60could have used a URL starting with 'ftp:', 'file:', etc.). However, it's the 61purpose of this tutorial to explain the more complicated cases, concentrating on 62HTTP. 63 64HTTP is based on requests and responses - the client makes requests and servers 65send responses. urllib2 mirrors this with a ``Request`` object which represents 66the HTTP request you are making. In its simplest form you create a Request 67object that specifies the URL you want to fetch. Calling ``urlopen`` with this 68Request object returns a response object for the URL requested. This response is 69a file-like object, which means you can for example call ``.read()`` on the 70response:: 71 72 import urllib2 73 74 req = urllib2.Request('http://www.voidspace.org.uk') 75 response = urllib2.urlopen(req) 76 the_page = response.read() 77 78Note that urllib2 makes use of the same Request interface to handle all URL 79schemes. For example, you can make an FTP request like so:: 80 81 req = urllib2.Request('ftp://example.com/') 82 83In the case of HTTP, there are two extra things that Request objects allow you 84to do: First, you can pass data to be sent to the server. Second, you can pass 85extra information ("metadata") *about* the data or the about request itself, to 86the server - this information is sent as HTTP "headers". Let's look at each of 87these in turn. 88 89Data 90---- 91 92Sometimes you want to send data to a URL (often the URL will refer to a CGI 93(Common Gateway Interface) script [#]_ or other web application). With HTTP, 94this is often done using what's known as a **POST** request. This is often what 95your browser does when you submit a HTML form that you filled in on the web. Not 96all POSTs have to come from forms: you can use a POST to transmit arbitrary data 97to your own application. In the common case of HTML forms, the data needs to be 98encoded in a standard way, and then passed to the Request object as the ``data`` 99argument. The encoding is done using a function from the ``urllib`` library 100*not* from ``urllib2``. :: 101 102 import urllib 103 import urllib2 104 105 url = 'http://www.someserver.com/cgi-bin/register.cgi' 106 values = {'name' : 'Michael Foord', 107 'location' : 'Northampton', 108 'language' : 'Python' } 109 110 data = urllib.urlencode(values) 111 req = urllib2.Request(url, data) 112 response = urllib2.urlopen(req) 113 the_page = response.read() 114 115Note that other encodings are sometimes required (e.g. for file upload from HTML 116forms - see `HTML Specification, Form Submission 117<https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13>`_ for more 118details). 119 120If you do not pass the ``data`` argument, urllib2 uses a **GET** request. One 121way in which GET and POST requests differ is that POST requests often have 122"side-effects": they change the state of the system in some way (for example by 123placing an order with the website for a hundredweight of tinned spam to be 124delivered to your door). Though the HTTP standard makes it clear that POSTs are 125intended to *always* cause side-effects, and GET requests *never* to cause 126side-effects, nothing prevents a GET request from having side-effects, nor a 127POST requests from having no side-effects. Data can also be passed in an HTTP 128GET request by encoding it in the URL itself. 129 130This is done as follows:: 131 132 >>> import urllib2 133 >>> import urllib 134 >>> data = {} 135 >>> data['name'] = 'Somebody Here' 136 >>> data['location'] = 'Northampton' 137 >>> data['language'] = 'Python' 138 >>> url_values = urllib.urlencode(data) 139 >>> print url_values # The order may differ. #doctest: +SKIP 140 name=Somebody+Here&language=Python&location=Northampton 141 >>> url = 'http://www.example.com/example.cgi' 142 >>> full_url = url + '?' + url_values 143 >>> data = urllib2.urlopen(full_url) 144 145Notice that the full URL is created by adding a ``?`` to the URL, followed by 146the encoded values. 147 148Headers 149------- 150 151We'll discuss here one particular HTTP header, to illustrate how to add headers 152to your HTTP request. 153 154Some websites [#]_ dislike being browsed by programs, or send different versions 155to different browsers [#]_. By default urllib2 identifies itself as 156``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version 157numbers of the Python release, 158e.g. ``Python-urllib/2.5``), which may confuse the site, or just plain 159not work. The way a browser identifies itself is through the 160``User-Agent`` header [#]_. When you create a Request object you can 161pass a dictionary of headers in. The following example makes the same 162request as above, but identifies itself as a version of Internet 163Explorer [#]_. :: 164 165 import urllib 166 import urllib2 167 168 url = 'http://www.someserver.com/cgi-bin/register.cgi' 169 user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' 170 values = {'name': 'Michael Foord', 171 'location': 'Northampton', 172 'language': 'Python' } 173 headers = {'User-Agent': user_agent} 174 175 data = urllib.urlencode(values) 176 req = urllib2.Request(url, data, headers) 177 response = urllib2.urlopen(req) 178 the_page = response.read() 179 180The response also has two useful methods. See the section on `info and geturl`_ 181which comes after we have a look at what happens when things go wrong. 182 183 184Handling Exceptions 185=================== 186 187*urlopen* raises :exc:`URLError` when it cannot handle a response (though as 188usual with Python APIs, built-in exceptions such as :exc:`ValueError`, 189:exc:`TypeError` etc. may also be raised). 190 191:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of 192HTTP URLs. 193 194URLError 195-------- 196 197Often, URLError is raised because there is no network connection (no route to 198the specified server), or the specified server doesn't exist. In this case, the 199exception raised will have a 'reason' attribute, which is a tuple containing an 200error code and a text error message. 201 202e.g. :: 203 204 >>> req = urllib2.Request('http://www.pretend_server.org') 205 >>> try: urllib2.urlopen(req) 206 ... except urllib2.URLError as e: 207 ... print e.reason #doctest: +SKIP 208 ... 209 (4, 'getaddrinfo failed') 210 211 212HTTPError 213--------- 214 215Every HTTP response from the server contains a numeric "status code". Sometimes 216the status code indicates that the server is unable to fulfil the request. The 217default handlers will handle some of these responses for you (for example, if 218the response is a "redirection" that requests the client fetch the document from 219a different URL, urllib2 will handle that for you). For those it can't handle, 220urlopen will raise an :exc:`HTTPError`. Typical errors include '404' (page not 221found), '403' (request forbidden), and '401' (authentication required). 222 223See section 10 of RFC 2616 for a reference on all the HTTP error codes. 224 225The :exc:`HTTPError` instance raised will have an integer 'code' attribute, which 226corresponds to the error sent by the server. 227 228Error Codes 229~~~~~~~~~~~ 230 231Because the default handlers handle redirects (codes in the 300 range), and 232codes in the 100--299 range indicate success, you will usually only see error 233codes in the 400--599 range. 234 235``BaseHTTPServer.BaseHTTPRequestHandler.responses`` is a useful dictionary of 236response codes in that shows all the response codes used by RFC 2616. The 237dictionary is reproduced here for convenience :: 238 239 # Table mapping response codes to messages; entries have the 240 # form {code: (shortmessage, longmessage)}. 241 responses = { 242 100: ('Continue', 'Request received, please continue'), 243 101: ('Switching Protocols', 244 'Switching to new protocol; obey Upgrade header'), 245 246 200: ('OK', 'Request fulfilled, document follows'), 247 201: ('Created', 'Document created, URL follows'), 248 202: ('Accepted', 249 'Request accepted, processing continues off-line'), 250 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 251 204: ('No Content', 'Request fulfilled, nothing follows'), 252 205: ('Reset Content', 'Clear input form for further input.'), 253 206: ('Partial Content', 'Partial content follows.'), 254 255 300: ('Multiple Choices', 256 'Object has several resources -- see URI list'), 257 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 258 302: ('Found', 'Object moved temporarily -- see URI list'), 259 303: ('See Other', 'Object moved -- see Method and URL list'), 260 304: ('Not Modified', 261 'Document has not changed since given time'), 262 305: ('Use Proxy', 263 'You must use proxy specified in Location to access this ' 264 'resource.'), 265 307: ('Temporary Redirect', 266 'Object moved temporarily -- see URI list'), 267 268 400: ('Bad Request', 269 'Bad request syntax or unsupported method'), 270 401: ('Unauthorized', 271 'No permission -- see authorization schemes'), 272 402: ('Payment Required', 273 'No payment -- see charging schemes'), 274 403: ('Forbidden', 275 'Request forbidden -- authorization will not help'), 276 404: ('Not Found', 'Nothing matches the given URI'), 277 405: ('Method Not Allowed', 278 'Specified method is invalid for this server.'), 279 406: ('Not Acceptable', 'URI not available in preferred format.'), 280 407: ('Proxy Authentication Required', 'You must authenticate with ' 281 'this proxy before proceeding.'), 282 408: ('Request Timeout', 'Request timed out; try again later.'), 283 409: ('Conflict', 'Request conflict.'), 284 410: ('Gone', 285 'URI no longer exists and has been permanently removed.'), 286 411: ('Length Required', 'Client must specify Content-Length.'), 287 412: ('Precondition Failed', 'Precondition in headers is false.'), 288 413: ('Request Entity Too Large', 'Entity is too large.'), 289 414: ('Request-URI Too Long', 'URI is too long.'), 290 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 291 416: ('Requested Range Not Satisfiable', 292 'Cannot satisfy request range.'), 293 417: ('Expectation Failed', 294 'Expect condition could not be satisfied.'), 295 296 500: ('Internal Server Error', 'Server got itself in trouble'), 297 501: ('Not Implemented', 298 'Server does not support this operation'), 299 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 300 503: ('Service Unavailable', 301 'The server cannot process the request due to a high load'), 302 504: ('Gateway Timeout', 303 'The gateway server did not receive a timely response'), 304 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), 305 } 306 307When an error is raised the server responds by returning an HTTP error code 308*and* an error page. You can use the :exc:`HTTPError` instance as a response on the 309page returned. This means that as well as the code attribute, it also has read, 310geturl, and info, methods. :: 311 312 >>> req = urllib2.Request('http://www.python.org/fish.html') 313 >>> try: 314 ... urllib2.urlopen(req) 315 ... except urllib2.HTTPError as e: 316 ... print e.code 317 ... print e.read() #doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE 318 ... 319 404 320 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 321 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 322 ... 323 <title>Page Not Found</title> 324 ... 325 326 327Wrapping it Up 328-------------- 329 330So if you want to be prepared for :exc:`HTTPError` *or* :exc:`URLError` there are two 331basic approaches. I prefer the second approach. 332 333Number 1 334~~~~~~~~ 335 336:: 337 338 339 from urllib2 import Request, urlopen, URLError, HTTPError 340 req = Request(someurl) 341 try: 342 response = urlopen(req) 343 except HTTPError as e: 344 print 'The server couldn\'t fulfill the request.' 345 print 'Error code: ', e.code 346 except URLError as e: 347 print 'We failed to reach a server.' 348 print 'Reason: ', e.reason 349 else: 350 # everything is fine 351 352 353.. note:: 354 355 The ``except HTTPError`` *must* come first, otherwise ``except URLError`` 356 will *also* catch an :exc:`HTTPError`. 357 358Number 2 359~~~~~~~~ 360 361:: 362 363 from urllib2 import Request, urlopen, URLError 364 req = Request(someurl) 365 try: 366 response = urlopen(req) 367 except URLError as e: 368 if hasattr(e, 'reason'): 369 print 'We failed to reach a server.' 370 print 'Reason: ', e.reason 371 elif hasattr(e, 'code'): 372 print 'The server couldn\'t fulfill the request.' 373 print 'Error code: ', e.code 374 else: 375 # everything is fine 376 377 378info and geturl 379=============== 380 381The response returned by urlopen (or the :exc:`HTTPError` instance) has two useful 382methods :meth:`info` and :meth:`geturl`. 383 384**geturl** - this returns the real URL of the page fetched. This is useful 385because ``urlopen`` (or the opener object used) may have followed a 386redirect. The URL of the page fetched may not be the same as the URL requested. 387 388**info** - this returns a dictionary-like object that describes the page 389fetched, particularly the headers sent by the server. It is currently an 390``httplib.HTTPMessage`` instance. 391 392Typical headers include 'Content-length', 'Content-type', and so on. See the 393`Quick Reference to HTTP Headers <https://www.cs.tut.fi/~jkorpela/http.html>`_ 394for a useful listing of HTTP headers with brief explanations of their meaning 395and use. 396 397 398Openers and Handlers 399==================== 400 401When you fetch a URL you use an opener (an instance of the perhaps 402confusingly-named :class:`urllib2.OpenerDirector`). Normally we have been using 403the default opener - via ``urlopen`` - but you can create custom 404openers. Openers use handlers. All the "heavy lifting" is done by the 405handlers. Each handler knows how to open URLs for a particular URL scheme (http, 406ftp, etc.), or how to handle an aspect of URL opening, for example HTTP 407redirections or HTTP cookies. 408 409You will want to create openers if you want to fetch URLs with specific handlers 410installed, for example to get an opener that handles cookies, or to get an 411opener that does not handle redirections. 412 413To create an opener, instantiate an ``OpenerDirector``, and then call 414``.add_handler(some_handler_instance)`` repeatedly. 415 416Alternatively, you can use ``build_opener``, which is a convenience function for 417creating opener objects with a single function call. ``build_opener`` adds 418several handlers by default, but provides a quick way to add more and/or 419override the default handlers. 420 421Other sorts of handlers you might want to can handle proxies, authentication, 422and other common but slightly specialised situations. 423 424``install_opener`` can be used to make an ``opener`` object the (global) default 425opener. This means that calls to ``urlopen`` will use the opener you have 426installed. 427 428Opener objects have an ``open`` method, which can be called directly to fetch 429urls in the same way as the ``urlopen`` function: there's no need to call 430``install_opener``, except as a convenience. 431 432 433Basic Authentication 434==================== 435 436To illustrate creating and installing a handler we will use the 437``HTTPBasicAuthHandler``. For a more detailed discussion of this subject -- 438including an explanation of how Basic Authentication works - see the `Basic 439Authentication Tutorial 440<http://www.voidspace.org.uk/python/articles/authentication.shtml>`_. 441 442When authentication is required, the server sends a header (as well as the 401 443error code) requesting authentication. This specifies the authentication scheme 444and a 'realm'. The header looks like: ``WWW-Authenticate: SCHEME 445realm="REALM"``. 446 447e.g. :: 448 449 WWW-Authenticate: Basic realm="cPanel Users" 450 451 452The client should then retry the request with the appropriate name and password 453for the realm included as a header in the request. This is 'basic 454authentication'. In order to simplify this process we can create an instance of 455``HTTPBasicAuthHandler`` and an opener to use this handler. 456 457The ``HTTPBasicAuthHandler`` uses an object called a password manager to handle 458the mapping of URLs and realms to passwords and usernames. If you know what the 459realm is (from the authentication header sent by the server), then you can use a 460``HTTPPasswordMgr``. Frequently one doesn't care what the realm is. In that 461case, it is convenient to use ``HTTPPasswordMgrWithDefaultRealm``. This allows 462you to specify a default username and password for a URL. This will be supplied 463in the absence of you providing an alternative combination for a specific 464realm. We indicate this by providing ``None`` as the realm argument to the 465``add_password`` method. 466 467The top-level URL is the first URL that requires authentication. URLs "deeper" 468than the URL you pass to .add_password() will also match. :: 469 470 # create a password manager 471 password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() 472 473 # Add the username and password. 474 # If we knew the realm, we could use it instead of None. 475 top_level_url = "http://example.com/foo/" 476 password_mgr.add_password(None, top_level_url, username, password) 477 478 handler = urllib2.HTTPBasicAuthHandler(password_mgr) 479 480 # create "opener" (OpenerDirector instance) 481 opener = urllib2.build_opener(handler) 482 483 # use the opener to fetch a URL 484 opener.open(a_url) 485 486 # Install the opener. 487 # Now all calls to urllib2.urlopen use our opener. 488 urllib2.install_opener(opener) 489 490.. note:: 491 492 In the above example we only supplied our ``HTTPBasicAuthHandler`` to 493 ``build_opener``. By default openers have the handlers for normal situations 494 -- ``ProxyHandler`` (if a proxy setting such as an :envvar:`http_proxy` 495 environment variable is set), ``UnknownHandler``, ``HTTPHandler``, 496 ``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``, 497 ``FileHandler``, ``HTTPErrorProcessor``. 498 499``top_level_url`` is in fact *either* a full URL (including the 'http:' scheme 500component and the hostname and optionally the port number) 501e.g. ``"http://example.com/"`` *or* an "authority" (i.e. the hostname, 502optionally including the port number) e.g. ``"example.com"`` or ``"example.com:8080"`` 503(the latter example includes a port number). The authority, if present, must 504NOT contain the "userinfo" component - for example ``"joe:password@example.com"`` is 505not correct. 506 507 508Proxies 509======= 510 511**urllib2** will auto-detect your proxy settings and use those. This is through 512the ``ProxyHandler``, which is part of the normal handler chain when a proxy 513setting is detected. Normally that's a good thing, but there are occasions 514when it may not be helpful [#]_. One way to do this is to setup our own 515``ProxyHandler``, with no proxies defined. This is done using similar steps to 516setting up a `Basic Authentication`_ handler: :: 517 518 >>> proxy_support = urllib2.ProxyHandler({}) 519 >>> opener = urllib2.build_opener(proxy_support) 520 >>> urllib2.install_opener(opener) 521 522.. note:: 523 524 Currently ``urllib2`` *does not* support fetching of ``https`` locations 525 through a proxy. However, this can be enabled by extending urllib2 as 526 shown in the recipe [#]_. 527 528.. note:: 529 530 ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see 531 the documentation on :func:`~urllib.getproxies`. 532 533 534Sockets and Layers 535================== 536 537The Python support for fetching resources from the web is layered. urllib2 uses 538the httplib library, which in turn uses the socket library. 539 540As of Python 2.3 you can specify how long a socket should wait for a response 541before timing out. This can be useful in applications which have to fetch web 542pages. By default the socket module has *no timeout* and can hang. Currently, 543the socket timeout is not exposed at the httplib or urllib2 levels. However, 544you can set the default timeout globally for all sockets using :: 545 546 import socket 547 import urllib2 548 549 # timeout in seconds 550 timeout = 10 551 socket.setdefaulttimeout(timeout) 552 553 # this call to urllib2.urlopen now uses the default timeout 554 # we have set in the socket module 555 req = urllib2.Request('http://www.voidspace.org.uk') 556 response = urllib2.urlopen(req) 557 558 559------- 560 561 562Footnotes 563========= 564 565This document was reviewed and revised by John Lee. 566 567.. [#] For an introduction to the CGI protocol see 568 `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_. 569.. [#] Google for example. 570.. [#] Browser sniffing is a very bad practice for website design - building 571 sites using web standards is much more sensible. Unfortunately a lot of 572 sites still send different versions to different browsers. 573.. [#] The user agent for MSIE 6 is 574 *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'* 575.. [#] For details of more HTTP request headers, see 576 `Quick Reference to HTTP Headers`_. 577.. [#] In my case I have to use a proxy to access the internet at work. If you 578 attempt to fetch *localhost* URLs through this proxy it blocks them. IE 579 is set to use the proxy, which urllib2 picks up on. In order to test 580 scripts with a localhost server, I have to prevent urllib2 from using 581 the proxy. 582.. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe 583 <https://code.activestate.com/recipes/456195/>`_. 584 585