2009-12-19 13:57:51 -04:00
|
|
|
.. _urllib-howto:
|
|
|
|
|
2008-06-23 08:23:31 -03:00
|
|
|
***********************************************************
|
|
|
|
HOWTO Fetch Internet Resources Using The urllib Package
|
|
|
|
***********************************************************
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
:Author: `Michael Foord <http://www.voidspace.org.uk/python/index.shtml>`_
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2008-06-23 08:23:31 -03:00
|
|
|
There is a French translation of an earlier revision of this
|
2007-08-15 11:28:22 -03:00
|
|
|
HOWTO, available at `urllib2 - Le Manuel manquant
|
Merged revisions 61239-61249,61252-61257,61260-61264,61269-61275,61278-61279,61285-61286,61288-61290,61298,61303-61305,61312-61314,61317,61329,61332,61344,61350-61351,61363-61376,61378-61379,61382-61383,61387-61388,61392,61395-61396,61402-61403 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r61239 | andrew.kuchling | 2008-03-05 01:44:41 +0100 (Wed, 05 Mar 2008) | 1 line
Add more items; add fragmentary notes
........
r61240 | amaury.forgeotdarc | 2008-03-05 02:50:33 +0100 (Wed, 05 Mar 2008) | 13 lines
Issue#2238: some syntax errors from *args or **kwargs expressions
would give bogus error messages, because of untested exceptions::
>>> f(**g(1=2))
XXX undetected error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
instead of the expected SyntaxError: keyword can't be an expression
Will backport.
........
r61241 | neal.norwitz | 2008-03-05 06:10:48 +0100 (Wed, 05 Mar 2008) | 3 lines
Remove the files/dirs after closing the DB so the tests work on Windows.
Patch from Trent Nelson. Also simplified removing a file by using test_support.
........
r61242 | neal.norwitz | 2008-03-05 06:14:18 +0100 (Wed, 05 Mar 2008) | 3 lines
Get this test to pass even when there is no sound card in the system.
Patch from Trent Nelson. (I can't test this.)
........
r61243 | neal.norwitz | 2008-03-05 06:20:44 +0100 (Wed, 05 Mar 2008) | 3 lines
Catch OSError when trying to remove a file in case removal fails. This
should prevent a failure in tearDown masking any real test failure.
........
r61244 | neal.norwitz | 2008-03-05 06:38:06 +0100 (Wed, 05 Mar 2008) | 5 lines
Make the timeout longer to give slow machines a chance to pass the test
before timing out. This doesn't change the duration of the test under
normal circumstances. This is targetted at fixing the spurious failures
on the FreeBSD buildbot primarily.
........
r61245 | neal.norwitz | 2008-03-05 06:49:03 +0100 (Wed, 05 Mar 2008) | 1 line
Tabs -> spaces
........
r61246 | neal.norwitz | 2008-03-05 06:50:20 +0100 (Wed, 05 Mar 2008) | 1 line
Use -u urlfetch to run more tests
........
r61247 | neal.norwitz | 2008-03-05 06:51:20 +0100 (Wed, 05 Mar 2008) | 1 line
test_smtplib sometimes reports leaks too, suppress it
........
r61248 | jeffrey.yasskin | 2008-03-05 07:19:56 +0100 (Wed, 05 Mar 2008) | 5 lines
Fix test_socketserver on Windows after r61099 added several signal.alarm()
calls (which don't exist on non-Unix platforms).
Thanks to Trent Nelson for the report and patch.
........
r61249 | georg.brandl | 2008-03-05 08:10:35 +0100 (Wed, 05 Mar 2008) | 2 lines
Fix some rst.
........
r61252 | thomas.heller | 2008-03-05 15:53:39 +0100 (Wed, 05 Mar 2008) | 2 lines
News entry for yesterdays commit.
........
r61253 | thomas.heller | 2008-03-05 16:34:29 +0100 (Wed, 05 Mar 2008) | 3 lines
Issue 1872: Changed the struct module typecode from 't' to '?', for
compatibility with PEP3118.
........
r61254 | skip.montanaro | 2008-03-05 17:41:09 +0100 (Wed, 05 Mar 2008) | 4 lines
Elaborate on the role of the altinstall target when installing multiple
versions.
........
r61255 | georg.brandl | 2008-03-05 20:31:44 +0100 (Wed, 05 Mar 2008) | 2 lines
#2239: PYTHONPATH delimiter is os.pathsep.
........
r61256 | raymond.hettinger | 2008-03-05 21:59:58 +0100 (Wed, 05 Mar 2008) | 1 line
C implementation of itertools.permutations().
........
r61257 | raymond.hettinger | 2008-03-05 22:04:32 +0100 (Wed, 05 Mar 2008) | 1 line
Small code cleanup.
........
r61260 | martin.v.loewis | 2008-03-05 23:24:31 +0100 (Wed, 05 Mar 2008) | 2 lines
cd PCbuild only after deleting all pyc files.
........
r61261 | raymond.hettinger | 2008-03-06 02:15:52 +0100 (Thu, 06 Mar 2008) | 1 line
Add examples.
........
r61262 | andrew.kuchling | 2008-03-06 02:36:27 +0100 (Thu, 06 Mar 2008) | 1 line
Add two items
........
r61263 | georg.brandl | 2008-03-06 07:47:18 +0100 (Thu, 06 Mar 2008) | 2 lines
#1725737: ignore other VC directories other than CVS and SVN's too.
........
r61264 | martin.v.loewis | 2008-03-06 07:55:22 +0100 (Thu, 06 Mar 2008) | 4 lines
Patch #2232: os.tmpfile might fail on Windows if the user has no
permission to create files in the root directory.
Will backport to 2.5.
........
r61269 | georg.brandl | 2008-03-06 08:19:15 +0100 (Thu, 06 Mar 2008) | 2 lines
Expand on re.split behavior with captured expressions.
........
r61270 | georg.brandl | 2008-03-06 08:22:09 +0100 (Thu, 06 Mar 2008) | 2 lines
Little clarification of assignments.
........
r61271 | georg.brandl | 2008-03-06 08:31:34 +0100 (Thu, 06 Mar 2008) | 2 lines
Add isinstance/issubclass to tutorial.
........
r61272 | georg.brandl | 2008-03-06 08:34:52 +0100 (Thu, 06 Mar 2008) | 2 lines
Add missing NEWS entry for r61263.
........
r61273 | georg.brandl | 2008-03-06 08:41:16 +0100 (Thu, 06 Mar 2008) | 2 lines
#2225: return nonzero status code from py_compile if not all files could be compiled.
........
r61274 | georg.brandl | 2008-03-06 08:43:02 +0100 (Thu, 06 Mar 2008) | 2 lines
#2220: handle matching failure more gracefully.
........
r61275 | georg.brandl | 2008-03-06 08:45:52 +0100 (Thu, 06 Mar 2008) | 2 lines
Bug #2220: handle rlcompleter attribute match failure more gracefully.
........
r61278 | martin.v.loewis | 2008-03-06 14:49:47 +0100 (Thu, 06 Mar 2008) | 1 line
Rely on x64 platform configuration when building _bsddb on AMD64.
........
r61279 | martin.v.loewis | 2008-03-06 14:50:28 +0100 (Thu, 06 Mar 2008) | 1 line
Update db-4.4.20 build procedure.
........
r61285 | raymond.hettinger | 2008-03-06 21:52:01 +0100 (Thu, 06 Mar 2008) | 1 line
More tests.
........
r61286 | raymond.hettinger | 2008-03-06 23:51:36 +0100 (Thu, 06 Mar 2008) | 1 line
Issue 2246: itertools grouper object did not participate in GC (should be backported).
........
r61288 | raymond.hettinger | 2008-03-07 02:33:20 +0100 (Fri, 07 Mar 2008) | 1 line
Tweak recipes and tests
........
r61289 | jeffrey.yasskin | 2008-03-07 07:22:15 +0100 (Fri, 07 Mar 2008) | 5 lines
Progress on issue #1193577 by adding a polling .shutdown() method to
SocketServers. The core of the patch was written by Pedro Werneck, but any bugs
are mine. I've also rearranged the code for timeouts in order to avoid
interfering with the shutdown poll.
........
r61290 | nick.coghlan | 2008-03-07 15:13:28 +0100 (Fri, 07 Mar 2008) | 1 line
Speed up with statements by storing the __exit__ method on the stack instead of in a temp variable (bumps the magic number for pyc files)
........
r61298 | andrew.kuchling | 2008-03-07 22:09:23 +0100 (Fri, 07 Mar 2008) | 1 line
Grammar fix
........
r61303 | georg.brandl | 2008-03-08 10:54:06 +0100 (Sat, 08 Mar 2008) | 2 lines
#2253: fix continue vs. finally docs.
........
r61304 | marc-andre.lemburg | 2008-03-08 11:01:43 +0100 (Sat, 08 Mar 2008) | 3 lines
Add new name for Mandrake: Mandriva.
........
r61305 | georg.brandl | 2008-03-08 11:05:24 +0100 (Sat, 08 Mar 2008) | 2 lines
#1533486: fix types in refcount intro.
........
r61312 | facundo.batista | 2008-03-08 17:50:27 +0100 (Sat, 08 Mar 2008) | 5 lines
Issue 1106316. post_mortem()'s parameter, traceback, is now
optional: it defaults to the traceback of the exception that is currently
being handled.
........
r61313 | jeffrey.yasskin | 2008-03-08 19:26:54 +0100 (Sat, 08 Mar 2008) | 2 lines
Add tests for with and finally performance to pybench.
........
r61314 | jeffrey.yasskin | 2008-03-08 21:08:21 +0100 (Sat, 08 Mar 2008) | 2 lines
Fix pybench for pythons < 2.6, tested back to 2.3.
........
r61317 | jeffrey.yasskin | 2008-03-08 22:35:15 +0100 (Sat, 08 Mar 2008) | 3 lines
Well that was dumb. platform.python_implementation returns a function, not a
string.
........
r61329 | georg.brandl | 2008-03-09 16:11:39 +0100 (Sun, 09 Mar 2008) | 2 lines
#2249: document assertTrue and assertFalse.
........
r61332 | neal.norwitz | 2008-03-09 20:03:42 +0100 (Sun, 09 Mar 2008) | 4 lines
Introduce a lock to fix a race condition which caused an exception in the test.
Some buildbots were consistently failing (e.g., amd64).
Also remove a couple of semi-colons.
........
r61344 | raymond.hettinger | 2008-03-11 01:19:07 +0100 (Tue, 11 Mar 2008) | 1 line
Add recipe to docs.
........
r61350 | guido.van.rossum | 2008-03-11 22:18:06 +0100 (Tue, 11 Mar 2008) | 3 lines
Fix the overflows in expandtabs(). "This time for sure!"
(Exploit at request.)
........
r61351 | raymond.hettinger | 2008-03-11 22:37:46 +0100 (Tue, 11 Mar 2008) | 1 line
Improve docs for itemgetter(). Show that it works with slices.
........
r61363 | georg.brandl | 2008-03-13 08:15:56 +0100 (Thu, 13 Mar 2008) | 2 lines
#2265: fix example.
........
r61364 | georg.brandl | 2008-03-13 08:17:14 +0100 (Thu, 13 Mar 2008) | 2 lines
#2270: fix typo.
........
r61365 | georg.brandl | 2008-03-13 08:21:41 +0100 (Thu, 13 Mar 2008) | 2 lines
#1720705: add docs about import/threading interaction, wording by Nick.
........
r61366 | andrew.kuchling | 2008-03-13 12:07:35 +0100 (Thu, 13 Mar 2008) | 1 line
Add class decorators
........
r61367 | raymond.hettinger | 2008-03-13 17:43:17 +0100 (Thu, 13 Mar 2008) | 1 line
Add 2-to-3 support for the itertools moved to builtins or renamed.
........
r61368 | raymond.hettinger | 2008-03-13 17:43:59 +0100 (Thu, 13 Mar 2008) | 1 line
Consistent tense.
........
r61369 | raymond.hettinger | 2008-03-13 20:03:51 +0100 (Thu, 13 Mar 2008) | 1 line
Issue 2274: Add heapq.heappushpop().
........
r61370 | raymond.hettinger | 2008-03-13 20:33:34 +0100 (Thu, 13 Mar 2008) | 1 line
Simplify the nlargest() code using heappushpop().
........
r61371 | brett.cannon | 2008-03-13 21:27:00 +0100 (Thu, 13 Mar 2008) | 4 lines
Move test_thread over to unittest. Commits GHOP 237.
Thanks Benjamin Peterson for the patch.
........
r61372 | brett.cannon | 2008-03-13 21:33:10 +0100 (Thu, 13 Mar 2008) | 4 lines
Move test_tokenize to doctest.
Done as GHOP 238 by Josip Dzolonga.
........
r61373 | brett.cannon | 2008-03-13 21:47:41 +0100 (Thu, 13 Mar 2008) | 4 lines
Convert test_contains, test_crypt, and test_select to unittest.
Patch from GHOP 294 by David Marek.
........
r61374 | brett.cannon | 2008-03-13 22:02:16 +0100 (Thu, 13 Mar 2008) | 4 lines
Move test_gdbm to use unittest.
Closes issue #1960. Thanks Giampaolo Rodola.
........
r61375 | brett.cannon | 2008-03-13 22:09:28 +0100 (Thu, 13 Mar 2008) | 4 lines
Convert test_fcntl to unittest.
Closes issue #2055. Thanks Giampaolo Rodola.
........
r61376 | raymond.hettinger | 2008-03-14 06:03:44 +0100 (Fri, 14 Mar 2008) | 1 line
Leave heapreplace() unchanged.
........
r61378 | martin.v.loewis | 2008-03-14 14:56:09 +0100 (Fri, 14 Mar 2008) | 2 lines
Patch #2284: add -x64 option to rt.bat.
........
r61379 | martin.v.loewis | 2008-03-14 14:57:59 +0100 (Fri, 14 Mar 2008) | 2 lines
Use -x64 flag.
........
r61382 | brett.cannon | 2008-03-14 15:03:10 +0100 (Fri, 14 Mar 2008) | 2 lines
Remove a bad test.
........
r61383 | mark.dickinson | 2008-03-14 15:23:37 +0100 (Fri, 14 Mar 2008) | 9 lines
Issue 705836: Fix struct.pack(">f", 1e40) to behave consistently
across platforms: it should now raise OverflowError on all
platforms. (Previously it raised OverflowError only on
non IEEE 754 platforms.)
Also fix the (already existing) test for this behaviour
so that it actually raises TestFailed instead of just
referencing it.
........
r61387 | thomas.heller | 2008-03-14 22:06:21 +0100 (Fri, 14 Mar 2008) | 1 line
Remove unneeded initializer.
........
r61388 | martin.v.loewis | 2008-03-14 22:19:28 +0100 (Fri, 14 Mar 2008) | 2 lines
Run debug version, cd to PCbuild.
........
r61392 | georg.brandl | 2008-03-15 00:10:34 +0100 (Sat, 15 Mar 2008) | 2 lines
Remove obsolete paragraph. #2288.
........
r61395 | georg.brandl | 2008-03-15 01:20:19 +0100 (Sat, 15 Mar 2008) | 2 lines
Fix lots of broken links in the docs, found by Sphinx' external link checker.
........
r61396 | skip.montanaro | 2008-03-15 03:32:49 +0100 (Sat, 15 Mar 2008) | 1 line
note that fork and forkpty raise OSError on failure
........
r61402 | skip.montanaro | 2008-03-15 17:04:45 +0100 (Sat, 15 Mar 2008) | 1 line
add %f format to datetime - issue 1158
........
r61403 | skip.montanaro | 2008-03-15 17:07:11 +0100 (Sat, 15 Mar 2008) | 2 lines
.
........
2008-03-15 21:07:10 -03:00
|
|
|
<http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml>`_.
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2009-01-03 17:18:54 -04:00
|
|
|
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
Introduction
|
|
|
|
============
|
|
|
|
|
|
|
|
.. sidebar:: Related Articles
|
|
|
|
|
|
|
|
You may also find useful the following article on fetching web resources
|
2008-06-23 08:23:31 -03:00
|
|
|
with Python:
|
2009-01-03 17:18:54 -04:00
|
|
|
|
2007-08-15 11:28:22 -03:00
|
|
|
* `Basic Authentication <http://www.voidspace.org.uk/python/articles/authentication.shtml>`_
|
2009-01-03 17:18:54 -04:00
|
|
|
|
2007-08-15 11:28:22 -03:00
|
|
|
A tutorial on *Basic Authentication*, with examples in Python.
|
|
|
|
|
2014-10-29 04:36:35 -03:00
|
|
|
**urllib.request** is a Python module for fetching URLs
|
2007-08-15 11:28:22 -03:00
|
|
|
(Uniform Resource Locators). It offers a very simple interface, in the form of
|
|
|
|
the *urlopen* function. This is capable of fetching URLs using a variety of
|
|
|
|
different protocols. It also offers a slightly more complex interface for
|
|
|
|
handling common situations - like basic authentication, cookies, proxies and so
|
|
|
|
on. These are provided by objects called handlers and openers.
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
urllib.request supports fetching URLs for many "URL schemes" (identified by the string
|
2007-08-15 11:28:22 -03:00
|
|
|
before the ":" in URL - for example "ftp" is the URL scheme of
|
|
|
|
"ftp://python.org/") using their associated network protocols (e.g. FTP, HTTP).
|
|
|
|
This tutorial focuses on the most common case, HTTP.
|
|
|
|
|
|
|
|
For straightforward situations *urlopen* is very easy to use. But as soon as you
|
|
|
|
encounter errors or non-trivial cases when opening HTTP URLs, you will need some
|
|
|
|
understanding of the HyperText Transfer Protocol. The most comprehensive and
|
|
|
|
authoritative reference to HTTP is :rfc:`2616`. This is a technical document and
|
2008-06-23 01:41:59 -03:00
|
|
|
not intended to be easy to read. This HOWTO aims to illustrate using *urllib*,
|
2007-08-15 11:28:22 -03:00
|
|
|
with enough detail about HTTP to help you through. It is not intended to replace
|
2008-06-23 01:41:59 -03:00
|
|
|
the :mod:`urllib.request` docs, but is supplementary to them.
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
|
|
|
|
Fetching URLs
|
|
|
|
=============
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
The simplest way to use urllib.request is as follows::
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
import urllib.request
|
2015-04-12 07:52:49 -03:00
|
|
|
with urllib.request.urlopen('http://python.org/') as response:
|
|
|
|
html = response.read()
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2012-03-13 23:29:33 -03:00
|
|
|
If you wish to retrieve a resource via URL and store it in a temporary location,
|
2013-10-13 17:09:14 -03:00
|
|
|
you can do so via the :func:`~urllib.request.urlretrieve` function::
|
2012-03-13 23:29:33 -03:00
|
|
|
|
|
|
|
import urllib.request
|
|
|
|
local_filename, headers = urllib.request.urlretrieve('http://python.org/')
|
|
|
|
html = open(local_filename)
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
Many uses of urllib will be that simple (note that instead of an 'http:' URL we
|
2007-08-15 11:28:22 -03:00
|
|
|
could have used an URL starting with 'ftp:', 'file:', etc.). However, it's the
|
|
|
|
purpose of this tutorial to explain the more complicated cases, concentrating on
|
|
|
|
HTTP.
|
|
|
|
|
|
|
|
HTTP is based on requests and responses - the client makes requests and servers
|
2008-06-23 01:41:59 -03:00
|
|
|
send responses. urllib.request mirrors this with a ``Request`` object which represents
|
2007-08-15 11:28:22 -03:00
|
|
|
the HTTP request you are making. In its simplest form you create a Request
|
|
|
|
object that specifies the URL you want to fetch. Calling ``urlopen`` with this
|
|
|
|
Request object returns a response object for the URL requested. This response is
|
|
|
|
a file-like object, which means you can for example call ``.read()`` on the
|
|
|
|
response::
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
import urllib.request
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
req = urllib.request.Request('http://www.voidspace.org.uk')
|
2015-04-12 07:52:49 -03:00
|
|
|
with urllib.request.urlopen(req) as response:
|
|
|
|
the_page = response.read()
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
Note that urllib.request makes use of the same Request interface to handle all URL
|
2007-08-15 11:28:22 -03:00
|
|
|
schemes. For example, you can make an FTP request like so::
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
req = urllib.request.Request('ftp://example.com/')
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
In the case of HTTP, there are two extra things that Request objects allow you
|
|
|
|
to do: First, you can pass data to be sent to the server. Second, you can pass
|
|
|
|
extra information ("metadata") *about* the data or the about request itself, to
|
|
|
|
the server - this information is sent as HTTP "headers". Let's look at each of
|
|
|
|
these in turn.
|
|
|
|
|
|
|
|
Data
|
|
|
|
----
|
|
|
|
|
|
|
|
Sometimes you want to send data to a URL (often the URL will refer to a CGI
|
2014-07-01 00:02:42 -03:00
|
|
|
(Common Gateway Interface) script or other web application). With HTTP,
|
2007-08-15 11:28:22 -03:00
|
|
|
this is often done using what's known as a **POST** request. This is often what
|
|
|
|
your browser does when you submit a HTML form that you filled in on the web. Not
|
|
|
|
all POSTs have to come from forms: you can use a POST to transmit arbitrary data
|
|
|
|
to your own application. In the common case of HTML forms, the data needs to be
|
|
|
|
encoded in a standard way, and then passed to the Request object as the ``data``
|
2008-06-23 08:23:31 -03:00
|
|
|
argument. The encoding is done using a function from the :mod:`urllib.parse`
|
|
|
|
library. ::
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
import urllib.parse
|
2009-01-03 17:18:54 -04:00
|
|
|
import urllib.request
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
url = 'http://www.someserver.com/cgi-bin/register.cgi'
|
|
|
|
values = {'name' : 'Michael Foord',
|
|
|
|
'location' : 'Northampton',
|
|
|
|
'language' : 'Python' }
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
data = urllib.parse.urlencode(values)
|
2012-03-14 22:08:13 -03:00
|
|
|
data = data.encode('utf-8') # data should be bytes
|
2008-06-23 01:41:59 -03:00
|
|
|
req = urllib.request.Request(url, data)
|
2015-04-12 07:52:49 -03:00
|
|
|
with urllib.request.urlopen(req) as response:
|
|
|
|
the_page = response.read()
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
Note that other encodings are sometimes required (e.g. for file upload from HTML
|
|
|
|
forms - see `HTML Specification, Form Submission
|
|
|
|
<http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13>`_ for more
|
|
|
|
details).
|
|
|
|
|
2008-06-23 08:23:31 -03:00
|
|
|
If you do not pass the ``data`` argument, urllib uses a **GET** request. One
|
2007-08-15 11:28:22 -03:00
|
|
|
way in which GET and POST requests differ is that POST requests often have
|
|
|
|
"side-effects": they change the state of the system in some way (for example by
|
|
|
|
placing an order with the website for a hundredweight of tinned spam to be
|
|
|
|
delivered to your door). Though the HTTP standard makes it clear that POSTs are
|
|
|
|
intended to *always* cause side-effects, and GET requests *never* to cause
|
|
|
|
side-effects, nothing prevents a GET request from having side-effects, nor a
|
|
|
|
POST requests from having no side-effects. Data can also be passed in an HTTP
|
|
|
|
GET request by encoding it in the URL itself.
|
|
|
|
|
|
|
|
This is done as follows::
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
>>> import urllib.request
|
|
|
|
>>> import urllib.parse
|
2007-08-15 11:28:22 -03:00
|
|
|
>>> data = {}
|
|
|
|
>>> data['name'] = 'Somebody Here'
|
|
|
|
>>> data['location'] = 'Northampton'
|
|
|
|
>>> data['language'] = 'Python'
|
2008-06-23 01:41:59 -03:00
|
|
|
>>> url_values = urllib.parse.urlencode(data)
|
2012-10-09 04:38:17 -03:00
|
|
|
>>> print(url_values) # The order may differ from below. #doctest: +SKIP
|
2007-08-15 11:28:22 -03:00
|
|
|
name=Somebody+Here&language=Python&location=Northampton
|
|
|
|
>>> url = 'http://www.example.com/example.cgi'
|
|
|
|
>>> full_url = url + '?' + url_values
|
2011-07-23 03:04:40 -03:00
|
|
|
>>> data = urllib.request.urlopen(full_url)
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
Notice that the full URL is created by adding a ``?`` to the URL, followed by
|
|
|
|
the encoded values.
|
|
|
|
|
|
|
|
Headers
|
|
|
|
-------
|
|
|
|
|
|
|
|
We'll discuss here one particular HTTP header, to illustrate how to add headers
|
|
|
|
to your HTTP request.
|
|
|
|
|
|
|
|
Some websites [#]_ dislike being browsed by programs, or send different versions
|
2013-12-23 12:20:51 -04:00
|
|
|
to different browsers [#]_. By default urllib identifies itself as
|
2007-08-15 11:28:22 -03:00
|
|
|
``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version
|
|
|
|
numbers of the Python release,
|
|
|
|
e.g. ``Python-urllib/2.5``), which may confuse the site, or just plain
|
|
|
|
not work. The way a browser identifies itself is through the
|
|
|
|
``User-Agent`` header [#]_. When you create a Request object you can
|
|
|
|
pass a dictionary of headers in. The following example makes the same
|
|
|
|
request as above, but identifies itself as a version of Internet
|
|
|
|
Explorer [#]_. ::
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
import urllib.parse
|
2009-01-03 17:18:54 -04:00
|
|
|
import urllib.request
|
|
|
|
|
2007-08-15 11:28:22 -03:00
|
|
|
url = 'http://www.someserver.com/cgi-bin/register.cgi'
|
2015-09-20 15:16:45 -03:00
|
|
|
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
|
2007-08-15 11:28:22 -03:00
|
|
|
values = {'name' : 'Michael Foord',
|
|
|
|
'location' : 'Northampton',
|
|
|
|
'language' : 'Python' }
|
|
|
|
headers = { 'User-Agent' : user_agent }
|
2009-01-03 17:18:54 -04:00
|
|
|
|
2012-03-14 22:08:13 -03:00
|
|
|
data = urllib.parse.urlencode(values)
|
|
|
|
data = data.encode('utf-8')
|
2008-06-23 01:41:59 -03:00
|
|
|
req = urllib.request.Request(url, data, headers)
|
2015-04-12 07:52:49 -03:00
|
|
|
with urllib.request.urlopen(req) as response:
|
|
|
|
the_page = response.read()
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
The response also has two useful methods. See the section on `info and geturl`_
|
|
|
|
which comes after we have a look at what happens when things go wrong.
|
|
|
|
|
|
|
|
|
|
|
|
Handling Exceptions
|
|
|
|
===================
|
|
|
|
|
2009-07-26 11:54:51 -03:00
|
|
|
*urlopen* raises :exc:`URLError` when it cannot handle a response (though as
|
|
|
|
usual with Python APIs, built-in exceptions such as :exc:`ValueError`,
|
|
|
|
:exc:`TypeError` etc. may also be raised).
|
2007-08-15 11:28:22 -03:00
|
|
|
|
Merged revisions 66670,66681,66688,66696-66699 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r66670 | georg.brandl | 2008-09-28 15:01:36 -0500 (Sun, 28 Sep 2008) | 2 lines
Don't show version in title.
........
r66681 | georg.brandl | 2008-09-29 11:51:35 -0500 (Mon, 29 Sep 2008) | 2 lines
Update nasm location.
........
r66688 | jesse.noller | 2008-09-29 19:15:45 -0500 (Mon, 29 Sep 2008) | 2 lines
issue3770: if SEM_OPEN is 0, disable the mp.synchronize module, rev. Nick Coghlan, Damien Miller
........
r66696 | andrew.kuchling | 2008-09-30 07:31:07 -0500 (Tue, 30 Sep 2008) | 1 line
Edits, and add markup
........
r66697 | andrew.kuchling | 2008-09-30 08:00:34 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fix
........
r66698 | andrew.kuchling | 2008-09-30 08:00:51 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes
........
r66699 | andrew.kuchling | 2008-09-30 08:01:46 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes. (optparse.rst probably needs an entire revision pass.)
........
2008-10-04 19:00:42 -03:00
|
|
|
:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of
|
2007-08-15 11:28:22 -03:00
|
|
|
HTTP URLs.
|
|
|
|
|
2008-06-23 08:23:31 -03:00
|
|
|
The exception classes are exported from the :mod:`urllib.error` module.
|
|
|
|
|
2007-08-15 11:28:22 -03:00
|
|
|
URLError
|
|
|
|
--------
|
|
|
|
|
|
|
|
Often, URLError is raised because there is no network connection (no route to
|
|
|
|
the specified server), or the specified server doesn't exist. In this case, the
|
|
|
|
exception raised will have a 'reason' attribute, which is a tuple containing an
|
|
|
|
error code and a text error message.
|
|
|
|
|
|
|
|
e.g. ::
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
>>> req = urllib.request.Request('http://www.pretend_server.org')
|
|
|
|
>>> try: urllib.request.urlopen(req)
|
2012-10-09 04:38:17 -03:00
|
|
|
... except urllib.error.URLError as e:
|
|
|
|
... print(e.reason) #doctest: +SKIP
|
|
|
|
...
|
2007-08-15 11:28:22 -03:00
|
|
|
(4, 'getaddrinfo failed')
|
|
|
|
|
|
|
|
|
|
|
|
HTTPError
|
|
|
|
---------
|
|
|
|
|
|
|
|
Every HTTP response from the server contains a numeric "status code". Sometimes
|
|
|
|
the status code indicates that the server is unable to fulfil the request. The
|
|
|
|
default handlers will handle some of these responses for you (for example, if
|
|
|
|
the response is a "redirection" that requests the client fetch the document from
|
2008-06-23 08:23:31 -03:00
|
|
|
a different URL, urllib will handle that for you). For those it can't handle,
|
Merged revisions 66670,66681,66688,66696-66699 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r66670 | georg.brandl | 2008-09-28 15:01:36 -0500 (Sun, 28 Sep 2008) | 2 lines
Don't show version in title.
........
r66681 | georg.brandl | 2008-09-29 11:51:35 -0500 (Mon, 29 Sep 2008) | 2 lines
Update nasm location.
........
r66688 | jesse.noller | 2008-09-29 19:15:45 -0500 (Mon, 29 Sep 2008) | 2 lines
issue3770: if SEM_OPEN is 0, disable the mp.synchronize module, rev. Nick Coghlan, Damien Miller
........
r66696 | andrew.kuchling | 2008-09-30 07:31:07 -0500 (Tue, 30 Sep 2008) | 1 line
Edits, and add markup
........
r66697 | andrew.kuchling | 2008-09-30 08:00:34 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fix
........
r66698 | andrew.kuchling | 2008-09-30 08:00:51 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes
........
r66699 | andrew.kuchling | 2008-09-30 08:01:46 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes. (optparse.rst probably needs an entire revision pass.)
........
2008-10-04 19:00:42 -03:00
|
|
|
urlopen will raise an :exc:`HTTPError`. Typical errors include '404' (page not
|
2007-08-15 11:28:22 -03:00
|
|
|
found), '403' (request forbidden), and '401' (authentication required).
|
|
|
|
|
|
|
|
See section 10 of RFC 2616 for a reference on all the HTTP error codes.
|
|
|
|
|
Merged revisions 66670,66681,66688,66696-66699 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r66670 | georg.brandl | 2008-09-28 15:01:36 -0500 (Sun, 28 Sep 2008) | 2 lines
Don't show version in title.
........
r66681 | georg.brandl | 2008-09-29 11:51:35 -0500 (Mon, 29 Sep 2008) | 2 lines
Update nasm location.
........
r66688 | jesse.noller | 2008-09-29 19:15:45 -0500 (Mon, 29 Sep 2008) | 2 lines
issue3770: if SEM_OPEN is 0, disable the mp.synchronize module, rev. Nick Coghlan, Damien Miller
........
r66696 | andrew.kuchling | 2008-09-30 07:31:07 -0500 (Tue, 30 Sep 2008) | 1 line
Edits, and add markup
........
r66697 | andrew.kuchling | 2008-09-30 08:00:34 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fix
........
r66698 | andrew.kuchling | 2008-09-30 08:00:51 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes
........
r66699 | andrew.kuchling | 2008-09-30 08:01:46 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes. (optparse.rst probably needs an entire revision pass.)
........
2008-10-04 19:00:42 -03:00
|
|
|
The :exc:`HTTPError` instance raised will have an integer 'code' attribute, which
|
2007-08-15 11:28:22 -03:00
|
|
|
corresponds to the error sent by the server.
|
|
|
|
|
|
|
|
Error Codes
|
|
|
|
~~~~~~~~~~~
|
|
|
|
|
|
|
|
Because the default handlers handle redirects (codes in the 300 range), and
|
|
|
|
codes in the 100-299 range indicate success, you will usually only see error
|
|
|
|
codes in the 400-599 range.
|
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
:attr:`http.server.BaseHTTPRequestHandler.responses` is a useful dictionary of
|
2007-08-15 11:28:22 -03:00
|
|
|
response codes in that shows all the response codes used by RFC 2616. The
|
|
|
|
dictionary is reproduced here for convenience ::
|
|
|
|
|
|
|
|
# Table mapping response codes to messages; entries have the
|
|
|
|
# form {code: (shortmessage, longmessage)}.
|
|
|
|
responses = {
|
|
|
|
100: ('Continue', 'Request received, please continue'),
|
|
|
|
101: ('Switching Protocols',
|
|
|
|
'Switching to new protocol; obey Upgrade header'),
|
|
|
|
|
|
|
|
200: ('OK', 'Request fulfilled, document follows'),
|
|
|
|
201: ('Created', 'Document created, URL follows'),
|
|
|
|
202: ('Accepted',
|
|
|
|
'Request accepted, processing continues off-line'),
|
|
|
|
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
|
|
|
|
204: ('No Content', 'Request fulfilled, nothing follows'),
|
|
|
|
205: ('Reset Content', 'Clear input form for further input.'),
|
|
|
|
206: ('Partial Content', 'Partial content follows.'),
|
|
|
|
|
|
|
|
300: ('Multiple Choices',
|
|
|
|
'Object has several resources -- see URI list'),
|
|
|
|
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
|
|
|
|
302: ('Found', 'Object moved temporarily -- see URI list'),
|
|
|
|
303: ('See Other', 'Object moved -- see Method and URL list'),
|
|
|
|
304: ('Not Modified',
|
|
|
|
'Document has not changed since given time'),
|
|
|
|
305: ('Use Proxy',
|
|
|
|
'You must use proxy specified in Location to access this '
|
|
|
|
'resource.'),
|
|
|
|
307: ('Temporary Redirect',
|
|
|
|
'Object moved temporarily -- see URI list'),
|
|
|
|
|
|
|
|
400: ('Bad Request',
|
|
|
|
'Bad request syntax or unsupported method'),
|
|
|
|
401: ('Unauthorized',
|
|
|
|
'No permission -- see authorization schemes'),
|
|
|
|
402: ('Payment Required',
|
|
|
|
'No payment -- see charging schemes'),
|
|
|
|
403: ('Forbidden',
|
|
|
|
'Request forbidden -- authorization will not help'),
|
|
|
|
404: ('Not Found', 'Nothing matches the given URI'),
|
|
|
|
405: ('Method Not Allowed',
|
|
|
|
'Specified method is invalid for this server.'),
|
|
|
|
406: ('Not Acceptable', 'URI not available in preferred format.'),
|
|
|
|
407: ('Proxy Authentication Required', 'You must authenticate with '
|
|
|
|
'this proxy before proceeding.'),
|
|
|
|
408: ('Request Timeout', 'Request timed out; try again later.'),
|
|
|
|
409: ('Conflict', 'Request conflict.'),
|
|
|
|
410: ('Gone',
|
|
|
|
'URI no longer exists and has been permanently removed.'),
|
|
|
|
411: ('Length Required', 'Client must specify Content-Length.'),
|
|
|
|
412: ('Precondition Failed', 'Precondition in headers is false.'),
|
|
|
|
413: ('Request Entity Too Large', 'Entity is too large.'),
|
|
|
|
414: ('Request-URI Too Long', 'URI is too long.'),
|
|
|
|
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
|
|
|
|
416: ('Requested Range Not Satisfiable',
|
|
|
|
'Cannot satisfy request range.'),
|
|
|
|
417: ('Expectation Failed',
|
|
|
|
'Expect condition could not be satisfied.'),
|
|
|
|
|
|
|
|
500: ('Internal Server Error', 'Server got itself in trouble'),
|
|
|
|
501: ('Not Implemented',
|
|
|
|
'Server does not support this operation'),
|
|
|
|
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
|
|
|
|
503: ('Service Unavailable',
|
|
|
|
'The server cannot process the request due to a high load'),
|
|
|
|
504: ('Gateway Timeout',
|
|
|
|
'The gateway server did not receive a timely response'),
|
|
|
|
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
|
|
|
|
}
|
|
|
|
|
|
|
|
When an error is raised the server responds by returning an HTTP error code
|
Merged revisions 66670,66681,66688,66696-66699 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r66670 | georg.brandl | 2008-09-28 15:01:36 -0500 (Sun, 28 Sep 2008) | 2 lines
Don't show version in title.
........
r66681 | georg.brandl | 2008-09-29 11:51:35 -0500 (Mon, 29 Sep 2008) | 2 lines
Update nasm location.
........
r66688 | jesse.noller | 2008-09-29 19:15:45 -0500 (Mon, 29 Sep 2008) | 2 lines
issue3770: if SEM_OPEN is 0, disable the mp.synchronize module, rev. Nick Coghlan, Damien Miller
........
r66696 | andrew.kuchling | 2008-09-30 07:31:07 -0500 (Tue, 30 Sep 2008) | 1 line
Edits, and add markup
........
r66697 | andrew.kuchling | 2008-09-30 08:00:34 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fix
........
r66698 | andrew.kuchling | 2008-09-30 08:00:51 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes
........
r66699 | andrew.kuchling | 2008-09-30 08:01:46 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes. (optparse.rst probably needs an entire revision pass.)
........
2008-10-04 19:00:42 -03:00
|
|
|
*and* an error page. You can use the :exc:`HTTPError` instance as a response on the
|
2007-08-15 11:28:22 -03:00
|
|
|
page returned. This means that as well as the code attribute, it also has read,
|
2008-06-23 01:41:59 -03:00
|
|
|
geturl, and info, methods as returned by the ``urllib.response`` module::
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
>>> req = urllib.request.Request('http://www.python.org/fish.html')
|
2009-01-03 17:18:54 -04:00
|
|
|
>>> try:
|
2012-10-09 04:38:17 -03:00
|
|
|
... urllib.request.urlopen(req)
|
|
|
|
... except urllib.error.HTTPError as e:
|
|
|
|
... print(e.code)
|
|
|
|
... print(e.read()) #doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
|
|
|
|
...
|
2007-08-15 11:28:22 -03:00
|
|
|
404
|
2012-10-09 04:38:17 -03:00
|
|
|
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
|
|
|
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
|
|
|
|
...
|
|
|
|
<title>Page Not Found</title>\n
|
|
|
|
...
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
Wrapping it Up
|
|
|
|
--------------
|
|
|
|
|
Merged revisions 66670,66681,66688,66696-66699 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r66670 | georg.brandl | 2008-09-28 15:01:36 -0500 (Sun, 28 Sep 2008) | 2 lines
Don't show version in title.
........
r66681 | georg.brandl | 2008-09-29 11:51:35 -0500 (Mon, 29 Sep 2008) | 2 lines
Update nasm location.
........
r66688 | jesse.noller | 2008-09-29 19:15:45 -0500 (Mon, 29 Sep 2008) | 2 lines
issue3770: if SEM_OPEN is 0, disable the mp.synchronize module, rev. Nick Coghlan, Damien Miller
........
r66696 | andrew.kuchling | 2008-09-30 07:31:07 -0500 (Tue, 30 Sep 2008) | 1 line
Edits, and add markup
........
r66697 | andrew.kuchling | 2008-09-30 08:00:34 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fix
........
r66698 | andrew.kuchling | 2008-09-30 08:00:51 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes
........
r66699 | andrew.kuchling | 2008-09-30 08:01:46 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes. (optparse.rst probably needs an entire revision pass.)
........
2008-10-04 19:00:42 -03:00
|
|
|
So if you want to be prepared for :exc:`HTTPError` *or* :exc:`URLError` there are two
|
2007-08-15 11:28:22 -03:00
|
|
|
basic approaches. I prefer the second approach.
|
|
|
|
|
|
|
|
Number 1
|
|
|
|
~~~~~~~~
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
from urllib.request import Request, urlopen
|
|
|
|
from urllib.error import URLError, HTTPError
|
2007-08-15 11:28:22 -03:00
|
|
|
req = Request(someurl)
|
|
|
|
try:
|
|
|
|
response = urlopen(req)
|
2009-05-12 08:19:14 -03:00
|
|
|
except HTTPError as e:
|
2007-09-04 04:15:32 -03:00
|
|
|
print('The server couldn\'t fulfill the request.')
|
|
|
|
print('Error code: ', e.code)
|
2009-05-12 08:19:14 -03:00
|
|
|
except URLError as e:
|
2007-09-04 04:15:32 -03:00
|
|
|
print('We failed to reach a server.')
|
|
|
|
print('Reason: ', e.reason)
|
2007-08-15 11:28:22 -03:00
|
|
|
else:
|
|
|
|
# everything is fine
|
|
|
|
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
The ``except HTTPError`` *must* come first, otherwise ``except URLError``
|
Merged revisions 66670,66681,66688,66696-66699 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r66670 | georg.brandl | 2008-09-28 15:01:36 -0500 (Sun, 28 Sep 2008) | 2 lines
Don't show version in title.
........
r66681 | georg.brandl | 2008-09-29 11:51:35 -0500 (Mon, 29 Sep 2008) | 2 lines
Update nasm location.
........
r66688 | jesse.noller | 2008-09-29 19:15:45 -0500 (Mon, 29 Sep 2008) | 2 lines
issue3770: if SEM_OPEN is 0, disable the mp.synchronize module, rev. Nick Coghlan, Damien Miller
........
r66696 | andrew.kuchling | 2008-09-30 07:31:07 -0500 (Tue, 30 Sep 2008) | 1 line
Edits, and add markup
........
r66697 | andrew.kuchling | 2008-09-30 08:00:34 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fix
........
r66698 | andrew.kuchling | 2008-09-30 08:00:51 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes
........
r66699 | andrew.kuchling | 2008-09-30 08:01:46 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes. (optparse.rst probably needs an entire revision pass.)
........
2008-10-04 19:00:42 -03:00
|
|
|
will *also* catch an :exc:`HTTPError`.
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
Number 2
|
|
|
|
~~~~~~~~
|
|
|
|
|
|
|
|
::
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
from urllib.request import Request, urlopen
|
|
|
|
from urllib.error import URLError
|
2007-08-15 11:28:22 -03:00
|
|
|
req = Request(someurl)
|
|
|
|
try:
|
|
|
|
response = urlopen(req)
|
2009-05-12 08:19:14 -03:00
|
|
|
except URLError as e:
|
2007-08-15 11:28:22 -03:00
|
|
|
if hasattr(e, 'reason'):
|
2007-09-04 04:15:32 -03:00
|
|
|
print('We failed to reach a server.')
|
|
|
|
print('Reason: ', e.reason)
|
2007-08-15 11:28:22 -03:00
|
|
|
elif hasattr(e, 'code'):
|
2007-09-04 04:15:32 -03:00
|
|
|
print('The server couldn\'t fulfill the request.')
|
|
|
|
print('Error code: ', e.code)
|
2007-08-15 11:28:22 -03:00
|
|
|
else:
|
|
|
|
# everything is fine
|
2009-01-03 17:18:54 -04:00
|
|
|
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
info and geturl
|
|
|
|
===============
|
|
|
|
|
Merged revisions 66670,66681,66688,66696-66699 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r66670 | georg.brandl | 2008-09-28 15:01:36 -0500 (Sun, 28 Sep 2008) | 2 lines
Don't show version in title.
........
r66681 | georg.brandl | 2008-09-29 11:51:35 -0500 (Mon, 29 Sep 2008) | 2 lines
Update nasm location.
........
r66688 | jesse.noller | 2008-09-29 19:15:45 -0500 (Mon, 29 Sep 2008) | 2 lines
issue3770: if SEM_OPEN is 0, disable the mp.synchronize module, rev. Nick Coghlan, Damien Miller
........
r66696 | andrew.kuchling | 2008-09-30 07:31:07 -0500 (Tue, 30 Sep 2008) | 1 line
Edits, and add markup
........
r66697 | andrew.kuchling | 2008-09-30 08:00:34 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fix
........
r66698 | andrew.kuchling | 2008-09-30 08:00:51 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes
........
r66699 | andrew.kuchling | 2008-09-30 08:01:46 -0500 (Tue, 30 Sep 2008) | 1 line
Markup fixes. (optparse.rst probably needs an entire revision pass.)
........
2008-10-04 19:00:42 -03:00
|
|
|
The response returned by urlopen (or the :exc:`HTTPError` instance) has two
|
|
|
|
useful methods :meth:`info` and :meth:`geturl` and is defined in the module
|
|
|
|
:mod:`urllib.response`..
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
**geturl** - this returns the real URL of the page fetched. This is useful
|
|
|
|
because ``urlopen`` (or the opener object used) may have followed a
|
|
|
|
redirect. The URL of the page fetched may not be the same as the URL requested.
|
|
|
|
|
|
|
|
**info** - this returns a dictionary-like object that describes the page
|
|
|
|
fetched, particularly the headers sent by the server. It is currently an
|
2008-06-23 08:23:31 -03:00
|
|
|
:class:`http.client.HTTPMessage` instance.
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
Typical headers include 'Content-length', 'Content-type', and so on. See the
|
|
|
|
`Quick Reference to HTTP Headers <http://www.cs.tut.fi/~jkorpela/http.html>`_
|
|
|
|
for a useful listing of HTTP headers with brief explanations of their meaning
|
|
|
|
and use.
|
|
|
|
|
|
|
|
|
|
|
|
Openers and Handlers
|
|
|
|
====================
|
|
|
|
|
|
|
|
When you fetch a URL you use an opener (an instance of the perhaps
|
2008-06-23 01:41:59 -03:00
|
|
|
confusingly-named :class:`urllib.request.OpenerDirector`). Normally we have been using
|
2007-08-15 11:28:22 -03:00
|
|
|
the default opener - via ``urlopen`` - but you can create custom
|
|
|
|
openers. Openers use handlers. All the "heavy lifting" is done by the
|
|
|
|
handlers. Each handler knows how to open URLs for a particular URL scheme (http,
|
|
|
|
ftp, etc.), or how to handle an aspect of URL opening, for example HTTP
|
|
|
|
redirections or HTTP cookies.
|
|
|
|
|
|
|
|
You will want to create openers if you want to fetch URLs with specific handlers
|
|
|
|
installed, for example to get an opener that handles cookies, or to get an
|
|
|
|
opener that does not handle redirections.
|
|
|
|
|
|
|
|
To create an opener, instantiate an ``OpenerDirector``, and then call
|
|
|
|
``.add_handler(some_handler_instance)`` repeatedly.
|
|
|
|
|
|
|
|
Alternatively, you can use ``build_opener``, which is a convenience function for
|
|
|
|
creating opener objects with a single function call. ``build_opener`` adds
|
|
|
|
several handlers by default, but provides a quick way to add more and/or
|
|
|
|
override the default handlers.
|
|
|
|
|
|
|
|
Other sorts of handlers you might want to can handle proxies, authentication,
|
|
|
|
and other common but slightly specialised situations.
|
|
|
|
|
|
|
|
``install_opener`` can be used to make an ``opener`` object the (global) default
|
|
|
|
opener. This means that calls to ``urlopen`` will use the opener you have
|
|
|
|
installed.
|
|
|
|
|
|
|
|
Opener objects have an ``open`` method, which can be called directly to fetch
|
|
|
|
urls in the same way as the ``urlopen`` function: there's no need to call
|
|
|
|
``install_opener``, except as a convenience.
|
|
|
|
|
|
|
|
|
|
|
|
Basic Authentication
|
|
|
|
====================
|
|
|
|
|
|
|
|
To illustrate creating and installing a handler we will use the
|
|
|
|
``HTTPBasicAuthHandler``. For a more detailed discussion of this subject --
|
|
|
|
including an explanation of how Basic Authentication works - see the `Basic
|
|
|
|
Authentication Tutorial
|
|
|
|
<http://www.voidspace.org.uk/python/articles/authentication.shtml>`_.
|
|
|
|
|
|
|
|
When authentication is required, the server sends a header (as well as the 401
|
|
|
|
error code) requesting authentication. This specifies the authentication scheme
|
2013-12-24 05:04:36 -04:00
|
|
|
and a 'realm'. The header looks like: ``WWW-Authenticate: SCHEME
|
2007-08-15 11:28:22 -03:00
|
|
|
realm="REALM"``.
|
|
|
|
|
2009-01-03 17:18:54 -04:00
|
|
|
e.g. ::
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2012-04-24 12:36:41 -03:00
|
|
|
WWW-Authenticate: Basic realm="cPanel Users"
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
|
|
|
|
The client should then retry the request with the appropriate name and password
|
|
|
|
for the realm included as a header in the request. This is 'basic
|
|
|
|
authentication'. In order to simplify this process we can create an instance of
|
|
|
|
``HTTPBasicAuthHandler`` and an opener to use this handler.
|
|
|
|
|
|
|
|
The ``HTTPBasicAuthHandler`` uses an object called a password manager to handle
|
|
|
|
the mapping of URLs and realms to passwords and usernames. If you know what the
|
|
|
|
realm is (from the authentication header sent by the server), then you can use a
|
|
|
|
``HTTPPasswordMgr``. Frequently one doesn't care what the realm is. In that
|
|
|
|
case, it is convenient to use ``HTTPPasswordMgrWithDefaultRealm``. This allows
|
|
|
|
you to specify a default username and password for a URL. This will be supplied
|
|
|
|
in the absence of you providing an alternative combination for a specific
|
|
|
|
realm. We indicate this by providing ``None`` as the realm argument to the
|
|
|
|
``add_password`` method.
|
|
|
|
|
|
|
|
The top-level URL is the first URL that requires authentication. URLs "deeper"
|
|
|
|
than the URL you pass to .add_password() will also match. ::
|
|
|
|
|
|
|
|
# create a password manager
|
2009-01-03 17:18:54 -04:00
|
|
|
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
# Add the username and password.
|
Merged revisions 68162,68166,68171,68176,68195-68196,68210,68232 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r68162 | ronald.oussoren | 2009-01-02 16:06:00 +0100 (Fri, 02 Jan 2009) | 3 lines
Fix for issue 4472 is incompatible with Cygwin, this patch
should fix that.
........
r68166 | benjamin.peterson | 2009-01-02 19:26:23 +0100 (Fri, 02 Jan 2009) | 1 line
document PyMemberDef
........
r68171 | georg.brandl | 2009-01-02 21:25:14 +0100 (Fri, 02 Jan 2009) | 3 lines
#4811: fix markup glitches (mostly remains of the conversion),
found by Gabriel Genellina.
........
r68176 | andrew.kuchling | 2009-01-02 22:00:35 +0100 (Fri, 02 Jan 2009) | 1 line
Add various items
........
r68195 | georg.brandl | 2009-01-03 14:45:15 +0100 (Sat, 03 Jan 2009) | 2 lines
Remove useless string literal.
........
r68196 | georg.brandl | 2009-01-03 15:29:53 +0100 (Sat, 03 Jan 2009) | 2 lines
Fix indentation.
........
r68210 | georg.brandl | 2009-01-03 20:10:12 +0100 (Sat, 03 Jan 2009) | 2 lines
Set eol-style correctly for mp_distributing.py.
........
r68232 | georg.brandl | 2009-01-03 22:52:16 +0100 (Sat, 03 Jan 2009) | 2 lines
Grammar fix.
........
2009-01-03 18:47:39 -04:00
|
|
|
# If we knew the realm, we could use it instead of None.
|
2007-08-15 11:28:22 -03:00
|
|
|
top_level_url = "http://example.com/foo/"
|
|
|
|
password_mgr.add_password(None, top_level_url, username, password)
|
|
|
|
|
2009-01-03 17:18:54 -04:00
|
|
|
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
# create "opener" (OpenerDirector instance)
|
2009-01-03 17:18:54 -04:00
|
|
|
opener = urllib.request.build_opener(handler)
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
# use the opener to fetch a URL
|
2009-01-03 17:18:54 -04:00
|
|
|
opener.open(a_url)
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
# Install the opener.
|
2008-06-23 01:41:59 -03:00
|
|
|
# Now all calls to urllib.request.urlopen use our opener.
|
2009-01-03 17:18:54 -04:00
|
|
|
urllib.request.install_opener(opener)
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2009-07-21 17:37:52 -03:00
|
|
|
In the above example we only supplied our ``HTTPBasicAuthHandler`` to
|
2007-08-15 11:28:22 -03:00
|
|
|
``build_opener``. By default openers have the handlers for normal situations
|
2013-04-28 12:07:16 -03:00
|
|
|
-- ``ProxyHandler`` (if a proxy setting such as an :envvar:`http_proxy`
|
|
|
|
environment variable is set), ``UnknownHandler``, ``HTTPHandler``,
|
2007-08-15 11:28:22 -03:00
|
|
|
``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``,
|
2013-04-28 12:07:16 -03:00
|
|
|
``FileHandler``, ``DataHandler``, ``HTTPErrorProcessor``.
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
``top_level_url`` is in fact *either* a full URL (including the 'http:' scheme
|
|
|
|
component and the hostname and optionally the port number)
|
|
|
|
e.g. "http://example.com/" *or* an "authority" (i.e. the hostname,
|
|
|
|
optionally including the port number) e.g. "example.com" or "example.com:8080"
|
|
|
|
(the latter example includes a port number). The authority, if present, must
|
|
|
|
NOT contain the "userinfo" component - for example "joe@password:example.com" is
|
|
|
|
not correct.
|
|
|
|
|
|
|
|
|
|
|
|
Proxies
|
|
|
|
=======
|
|
|
|
|
2008-06-23 08:23:31 -03:00
|
|
|
**urllib** will auto-detect your proxy settings and use those. This is through
|
2013-04-28 12:07:16 -03:00
|
|
|
the ``ProxyHandler``, which is part of the normal handler chain when a proxy
|
2013-04-28 12:24:35 -03:00
|
|
|
setting is detected. Normally that's a good thing, but there are occasions
|
|
|
|
when it may not be helpful [#]_. One way to do this is to setup our own
|
|
|
|
``ProxyHandler``, with no proxies defined. This is done using similar steps to
|
2013-12-24 05:04:36 -04:00
|
|
|
setting up a `Basic Authentication`_ handler: ::
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
>>> proxy_support = urllib.request.ProxyHandler({})
|
|
|
|
>>> opener = urllib.request.build_opener(proxy_support)
|
|
|
|
>>> urllib.request.install_opener(opener)
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
Currently ``urllib.request`` *does not* support fetching of ``https`` locations
|
|
|
|
through a proxy. However, this can be enabled by extending urllib.request as
|
2007-08-15 11:28:22 -03:00
|
|
|
shown in the recipe [#]_.
|
|
|
|
|
|
|
|
|
|
|
|
Sockets and Layers
|
|
|
|
==================
|
|
|
|
|
2008-06-23 08:23:31 -03:00
|
|
|
The Python support for fetching resources from the web is layered. urllib uses
|
|
|
|
the :mod:`http.client` library, which in turn uses the socket library.
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
As of Python 2.3 you can specify how long a socket should wait for a response
|
|
|
|
before timing out. This can be useful in applications which have to fetch web
|
|
|
|
pages. By default the socket module has *no timeout* and can hang. Currently,
|
2008-06-23 01:41:59 -03:00
|
|
|
the socket timeout is not exposed at the http.client or urllib.request levels.
|
2008-05-26 13:32:26 -03:00
|
|
|
However, you can set the default timeout globally for all sockets using ::
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
import socket
|
2008-06-23 01:41:59 -03:00
|
|
|
import urllib.request
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
# timeout in seconds
|
|
|
|
timeout = 10
|
2009-01-03 17:18:54 -04:00
|
|
|
socket.setdefaulttimeout(timeout)
|
2007-08-15 11:28:22 -03:00
|
|
|
|
2008-06-23 01:41:59 -03:00
|
|
|
# this call to urllib.request.urlopen now uses the default timeout
|
2007-08-15 11:28:22 -03:00
|
|
|
# we have set in the socket module
|
2008-06-23 01:41:59 -03:00
|
|
|
req = urllib.request.Request('http://www.voidspace.org.uk')
|
|
|
|
response = urllib.request.urlopen(req)
|
2007-08-15 11:28:22 -03:00
|
|
|
|
|
|
|
|
|
|
|
-------
|
|
|
|
|
|
|
|
|
|
|
|
Footnotes
|
|
|
|
=========
|
|
|
|
|
|
|
|
This document was reviewed and revised by John Lee.
|
|
|
|
|
2015-09-20 15:17:41 -03:00
|
|
|
.. [#] Google for example.
|
2007-08-15 11:28:22 -03:00
|
|
|
.. [#] Browser sniffing is a very bad practise for website design - building
|
|
|
|
sites using web standards is much more sensible. Unfortunately a lot of
|
|
|
|
sites still send different versions to different browsers.
|
|
|
|
.. [#] The user agent for MSIE 6 is
|
|
|
|
*'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'*
|
|
|
|
.. [#] For details of more HTTP request headers, see
|
|
|
|
`Quick Reference to HTTP Headers`_.
|
|
|
|
.. [#] In my case I have to use a proxy to access the internet at work. If you
|
|
|
|
attempt to fetch *localhost* URLs through this proxy it blocks them. IE
|
2008-06-23 08:23:31 -03:00
|
|
|
is set to use the proxy, which urllib picks up on. In order to test
|
|
|
|
scripts with a localhost server, I have to prevent urllib from using
|
2007-08-15 11:28:22 -03:00
|
|
|
the proxy.
|
2009-01-03 17:18:54 -04:00
|
|
|
.. [#] urllib opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe
|
2014-10-29 05:37:43 -03:00
|
|
|
<http://code.activestate.com/recipes/456195/>`_.
|
2009-01-03 17:18:54 -04:00
|
|
|
|