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