urllib2.html 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="HOWTO Fetch Internet Resources Using The urllib Package" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/howto/urllib2.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Author, Michael Foord,. Introduction: Related Articles: You may also find useful the following article on fetching web resources with Python: Basic Authentication A tutorial on Basic Authentication..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Author, Michael Foord,. Introduction: Related Articles: You may also find useful the following article on fetching web resources with Python: Basic Authentication A tutorial on Basic Authentication..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>HOWTO Fetch Internet Resources Using The urllib Package &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="Argparse Tutorial" href="argparse.html" />
  34. <link rel="prev" title="Unicode HOWTO" href="unicode.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/howto/urllib2.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">HOWTO Fetch Internet Resources Using The urllib Package</a><ul>
  86. <li><a class="reference internal" href="#introduction">Introduction</a></li>
  87. <li><a class="reference internal" href="#fetching-urls">Fetching URLs</a><ul>
  88. <li><a class="reference internal" href="#data">Data</a></li>
  89. <li><a class="reference internal" href="#headers">Headers</a></li>
  90. </ul>
  91. </li>
  92. <li><a class="reference internal" href="#handling-exceptions">Handling Exceptions</a><ul>
  93. <li><a class="reference internal" href="#urlerror">URLError</a></li>
  94. <li><a class="reference internal" href="#httperror">HTTPError</a><ul>
  95. <li><a class="reference internal" href="#error-codes">Error Codes</a></li>
  96. </ul>
  97. </li>
  98. <li><a class="reference internal" href="#wrapping-it-up">Wrapping it Up</a><ul>
  99. <li><a class="reference internal" href="#number-1">Number 1</a></li>
  100. <li><a class="reference internal" href="#number-2">Number 2</a></li>
  101. </ul>
  102. </li>
  103. </ul>
  104. </li>
  105. <li><a class="reference internal" href="#info-and-geturl">info and geturl</a></li>
  106. <li><a class="reference internal" href="#openers-and-handlers">Openers and Handlers</a></li>
  107. <li><a class="reference internal" href="#id5">Basic Authentication</a></li>
  108. <li><a class="reference internal" href="#proxies">Proxies</a></li>
  109. <li><a class="reference internal" href="#sockets-and-layers">Sockets and Layers</a></li>
  110. <li><a class="reference internal" href="#footnotes">Footnotes</a></li>
  111. </ul>
  112. </li>
  113. </ul>
  114. </div>
  115. <div>
  116. <h4>Previous topic</h4>
  117. <p class="topless"><a href="unicode.html"
  118. title="previous chapter">Unicode HOWTO</a></p>
  119. </div>
  120. <div>
  121. <h4>Next topic</h4>
  122. <p class="topless"><a href="argparse.html"
  123. title="next chapter">Argparse Tutorial</a></p>
  124. </div>
  125. <div role="note" aria-label="source link">
  126. <h3>This Page</h3>
  127. <ul class="this-page-menu">
  128. <li><a href="../bugs.html">Report a Bug</a></li>
  129. <li>
  130. <a href="https://github.com/python/cpython/blob/main/Doc/howto/urllib2.rst"
  131. rel="nofollow">Show Source
  132. </a>
  133. </li>
  134. </ul>
  135. </div>
  136. </nav>
  137. </div>
  138. </div>
  139. <div class="related" role="navigation" aria-label="related navigation">
  140. <h3>Navigation</h3>
  141. <ul>
  142. <li class="right" style="margin-right: 10px">
  143. <a href="../genindex.html" title="General Index"
  144. accesskey="I">index</a></li>
  145. <li class="right" >
  146. <a href="../py-modindex.html" title="Python Module Index"
  147. >modules</a> |</li>
  148. <li class="right" >
  149. <a href="argparse.html" title="Argparse Tutorial"
  150. accesskey="N">next</a> |</li>
  151. <li class="right" >
  152. <a href="unicode.html" title="Unicode HOWTO"
  153. accesskey="P">previous</a> |</li>
  154. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  155. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  156. <li class="switchers">
  157. <div class="language_switcher_placeholder"></div>
  158. <div class="version_switcher_placeholder"></div>
  159. </li>
  160. <li>
  161. </li>
  162. <li id="cpython-language-and-version">
  163. <a href="../index.html">3.12.0 Documentation</a> &#187;
  164. </li>
  165. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li>
  166. <li class="nav-item nav-item-this"><a href="">HOWTO Fetch Internet Resources Using The urllib Package</a></li>
  167. <li class="right">
  168. <div class="inline-search" role="search">
  169. <form class="inline-search" action="../search.html" method="get">
  170. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  171. <input type="submit" value="Go" />
  172. </form>
  173. </div>
  174. |
  175. </li>
  176. <li class="right">
  177. <label class="theme-selector-label">
  178. Theme
  179. <select class="theme-selector" oninput="activateTheme(this.value)">
  180. <option value="auto" selected>Auto</option>
  181. <option value="light">Light</option>
  182. <option value="dark">Dark</option>
  183. </select>
  184. </label> |</li>
  185. </ul>
  186. </div>
  187. <div class="document">
  188. <div class="documentwrapper">
  189. <div class="bodywrapper">
  190. <div class="body" role="main">
  191. <section id="howto-fetch-internet-resources-using-the-urllib-package">
  192. <span id="urllib-howto"></span><h1>HOWTO Fetch Internet Resources Using The urllib Package<a class="headerlink" href="#howto-fetch-internet-resources-using-the-urllib-package" title="Permalink to this headline">¶</a></h1>
  193. <dl class="field-list simple">
  194. <dt class="field-odd">Author</dt>
  195. <dd class="field-odd"><p><a class="reference external" href="https://agileabstractions.com/">Michael Foord</a></p>
  196. </dd>
  197. </dl>
  198. <section id="introduction">
  199. <h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
  200. <aside class="sidebar">
  201. <p class="sidebar-title">Related Articles</p>
  202. <p>You may also find useful the following article on fetching web resources
  203. with Python:</p>
  204. <ul>
  205. <li><p><a class="reference external" href="https://web.archive.org/web/20201215133350/http://www.voidspace.org.uk/python/articles/authentication.shtml">Basic Authentication</a></p>
  206. <blockquote>
  207. <div><p>A tutorial on <em>Basic Authentication</em>, with examples in Python.</p>
  208. </div></blockquote>
  209. </li>
  210. </ul>
  211. </aside>
  212. <p><strong>urllib.request</strong> is a Python module for fetching URLs
  213. (Uniform Resource Locators). It offers a very simple interface, in the form of
  214. the <em>urlopen</em> function. This is capable of fetching URLs using a variety of
  215. different protocols. It also offers a slightly more complex interface for
  216. handling common situations - like basic authentication, cookies, proxies and so
  217. on. These are provided by objects called handlers and openers.</p>
  218. <p>urllib.request supports fetching URLs for many “URL schemes” (identified by the string
  219. before the <code class="docutils literal notranslate"><span class="pre">&quot;:&quot;</span></code> in URL - for example <code class="docutils literal notranslate"><span class="pre">&quot;ftp&quot;</span></code> is the URL scheme of
  220. <code class="docutils literal notranslate"><span class="pre">&quot;ftp://python.org/&quot;</span></code>) using their associated network protocols (e.g. FTP, HTTP).
  221. This tutorial focuses on the most common case, HTTP.</p>
  222. <p>For straightforward situations <em>urlopen</em> is very easy to use. But as soon as you
  223. encounter errors or non-trivial cases when opening HTTP URLs, you will need some
  224. understanding of the HyperText Transfer Protocol. The most comprehensive and
  225. authoritative reference to HTTP is <span class="target" id="index-0"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2616.html"><strong>RFC 2616</strong></a>. This is a technical document and
  226. not intended to be easy to read. This HOWTO aims to illustrate using <em>urllib</em>,
  227. with enough detail about HTTP to help you through. It is not intended to replace
  228. the <a class="reference internal" href="../library/urllib.request.html#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.request</span></code></a> docs, but is supplementary to them.</p>
  229. </section>
  230. <section id="fetching-urls">
  231. <h2>Fetching URLs<a class="headerlink" href="#fetching-urls" title="Permalink to this headline">¶</a></h2>
  232. <p>The simplest way to use urllib.request is as follows:</p>
  233. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib.request</span>
  234. <span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://python.org/&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">response</span><span class="p">:</span>
  235. <span class="n">html</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
  236. </pre></div>
  237. </div>
  238. <p>If you wish to retrieve a resource via URL and store it in a temporary
  239. location, you can do so via the <a class="reference internal" href="../library/shutil.html#shutil.copyfileobj" title="shutil.copyfileobj"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copyfileobj()</span></code></a> and
  240. <a class="reference internal" href="../library/tempfile.html#tempfile.NamedTemporaryFile" title="tempfile.NamedTemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">tempfile.NamedTemporaryFile()</span></code></a> functions:</p>
  241. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">shutil</span>
  242. <span class="kn">import</span> <span class="nn">tempfile</span>
  243. <span class="kn">import</span> <span class="nn">urllib.request</span>
  244. <span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://python.org/&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">response</span><span class="p">:</span>
  245. <span class="k">with</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">NamedTemporaryFile</span><span class="p">(</span><span class="n">delete</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span> <span class="k">as</span> <span class="n">tmp_file</span><span class="p">:</span>
  246. <span class="n">shutil</span><span class="o">.</span><span class="n">copyfileobj</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="n">tmp_file</span><span class="p">)</span>
  247. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">tmp_file</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">as</span> <span class="n">html</span><span class="p">:</span>
  248. <span class="k">pass</span>
  249. </pre></div>
  250. </div>
  251. <p>Many uses of urllib will be that simple (note that instead of an ‘http:’ URL we
  252. could have used a URL starting with ‘ftp:’, ‘file:’, etc.). However, it’s the
  253. purpose of this tutorial to explain the more complicated cases, concentrating on
  254. HTTP.</p>
  255. <p>HTTP is based on requests and responses - the client makes requests and servers
  256. send responses. urllib.request mirrors this with a <code class="docutils literal notranslate"><span class="pre">Request</span></code> object which represents
  257. the HTTP request you are making. In its simplest form you create a Request
  258. object that specifies the URL you want to fetch. Calling <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> with this
  259. Request object returns a response object for the URL requested. This response is
  260. a file-like object, which means you can for example call <code class="docutils literal notranslate"><span class="pre">.read()</span></code> on the
  261. response:</p>
  262. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib.request</span>
  263. <span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://python.org/&#39;</span><span class="p">)</span>
  264. <span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span> <span class="k">as</span> <span class="n">response</span><span class="p">:</span>
  265. <span class="n">the_page</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
  266. </pre></div>
  267. </div>
  268. <p>Note that urllib.request makes use of the same Request interface to handle all URL
  269. schemes. For example, you can make an FTP request like so:</p>
  270. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;ftp://example.com/&#39;</span><span class="p">)</span>
  271. </pre></div>
  272. </div>
  273. <p>In the case of HTTP, there are two extra things that Request objects allow you
  274. to do: First, you can pass data to be sent to the server. Second, you can pass
  275. extra information (“metadata”) <em>about</em> the data or about the request itself, to
  276. the server - this information is sent as HTTP “headers”. Let’s look at each of
  277. these in turn.</p>
  278. <section id="data">
  279. <h3>Data<a class="headerlink" href="#data" title="Permalink to this headline">¶</a></h3>
  280. <p>Sometimes you want to send data to a URL (often the URL will refer to a CGI
  281. (Common Gateway Interface) script or other web application). With HTTP,
  282. this is often done using what’s known as a <strong>POST</strong> request. This is often what
  283. your browser does when you submit a HTML form that you filled in on the web. Not
  284. all POSTs have to come from forms: you can use a POST to transmit arbitrary data
  285. to your own application. In the common case of HTML forms, the data needs to be
  286. encoded in a standard way, and then passed to the Request object as the <code class="docutils literal notranslate"><span class="pre">data</span></code>
  287. argument. The encoding is done using a function from the <a class="reference internal" href="../library/urllib.parse.html#module-urllib.parse" title="urllib.parse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.parse</span></code></a>
  288. library.</p>
  289. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib.parse</span>
  290. <span class="kn">import</span> <span class="nn">urllib.request</span>
  291. <span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;http://www.someserver.com/cgi-bin/register.cgi&#39;</span>
  292. <span class="n">values</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span> <span class="p">:</span> <span class="s1">&#39;Michael Foord&#39;</span><span class="p">,</span>
  293. <span class="s1">&#39;location&#39;</span> <span class="p">:</span> <span class="s1">&#39;Northampton&#39;</span><span class="p">,</span>
  294. <span class="s1">&#39;language&#39;</span> <span class="p">:</span> <span class="s1">&#39;Python&#39;</span> <span class="p">}</span>
  295. <span class="n">data</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">parse</span><span class="o">.</span><span class="n">urlencode</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
  296. <span class="n">data</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;ascii&#39;</span><span class="p">)</span> <span class="c1"># data should be bytes</span>
  297. <span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
  298. <span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span> <span class="k">as</span> <span class="n">response</span><span class="p">:</span>
  299. <span class="n">the_page</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
  300. </pre></div>
  301. </div>
  302. <p>Note that other encodings are sometimes required (e.g. for file upload from HTML
  303. forms - see <a class="reference external" href="https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13">HTML Specification, Form Submission</a> for more
  304. details).</p>
  305. <p>If you do not pass the <code class="docutils literal notranslate"><span class="pre">data</span></code> argument, urllib uses a <strong>GET</strong> request. One
  306. way in which GET and POST requests differ is that POST requests often have
  307. “side-effects”: they change the state of the system in some way (for example by
  308. placing an order with the website for a hundredweight of tinned spam to be
  309. delivered to your door). Though the HTTP standard makes it clear that POSTs are
  310. intended to <em>always</em> cause side-effects, and GET requests <em>never</em> to cause
  311. side-effects, nothing prevents a GET request from having side-effects, nor a
  312. POST requests from having no side-effects. Data can also be passed in an HTTP
  313. GET request by encoding it in the URL itself.</p>
  314. <p>This is done as follows:</p>
  315. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.request</span>
  316. <span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.parse</span>
  317. <span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">{}</span>
  318. <span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Somebody Here&#39;</span>
  319. <span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;location&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Northampton&#39;</span>
  320. <span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;language&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
  321. <span class="gp">&gt;&gt;&gt; </span><span class="n">url_values</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">parse</span><span class="o">.</span><span class="n">urlencode</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
  322. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">url_values</span><span class="p">)</span> <span class="c1"># The order may differ from below. </span>
  323. <span class="go">name=Somebody+Here&amp;language=Python&amp;location=Northampton</span>
  324. <span class="gp">&gt;&gt;&gt; </span><span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;http://www.example.com/example.cgi&#39;</span>
  325. <span class="gp">&gt;&gt;&gt; </span><span class="n">full_url</span> <span class="o">=</span> <span class="n">url</span> <span class="o">+</span> <span class="s1">&#39;?&#39;</span> <span class="o">+</span> <span class="n">url_values</span>
  326. <span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">full_url</span><span class="p">)</span>
  327. </pre></div>
  328. </div>
  329. <p>Notice that the full URL is created by adding a <code class="docutils literal notranslate"><span class="pre">?</span></code> to the URL, followed by
  330. the encoded values.</p>
  331. </section>
  332. <section id="headers">
  333. <h3>Headers<a class="headerlink" href="#headers" title="Permalink to this headline">¶</a></h3>
  334. <p>We’ll discuss here one particular HTTP header, to illustrate how to add headers
  335. to your HTTP request.</p>
  336. <p>Some websites <a class="footnote-reference brackets" href="#id8" id="id1">1</a> dislike being browsed by programs, or send different versions
  337. to different browsers <a class="footnote-reference brackets" href="#id9" id="id2">2</a>. By default urllib identifies itself as
  338. <code class="docutils literal notranslate"><span class="pre">Python-urllib/x.y</span></code> (where <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> are the major and minor version
  339. numbers of the Python release,
  340. e.g. <code class="docutils literal notranslate"><span class="pre">Python-urllib/2.5</span></code>), which may confuse the site, or just plain
  341. not work. The way a browser identifies itself is through the
  342. <code class="docutils literal notranslate"><span class="pre">User-Agent</span></code> header <a class="footnote-reference brackets" href="#id10" id="id3">3</a>. When you create a Request object you can
  343. pass a dictionary of headers in. The following example makes the same
  344. request as above, but identifies itself as a version of Internet
  345. Explorer <a class="footnote-reference brackets" href="#id11" id="id4">4</a>.</p>
  346. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib.parse</span>
  347. <span class="kn">import</span> <span class="nn">urllib.request</span>
  348. <span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;http://www.someserver.com/cgi-bin/register.cgi&#39;</span>
  349. <span class="n">user_agent</span> <span class="o">=</span> <span class="s1">&#39;Mozilla/5.0 (Windows NT 6.1; Win64; x64)&#39;</span>
  350. <span class="n">values</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;Michael Foord&#39;</span><span class="p">,</span>
  351. <span class="s1">&#39;location&#39;</span><span class="p">:</span> <span class="s1">&#39;Northampton&#39;</span><span class="p">,</span>
  352. <span class="s1">&#39;language&#39;</span><span class="p">:</span> <span class="s1">&#39;Python&#39;</span> <span class="p">}</span>
  353. <span class="n">headers</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;User-Agent&#39;</span><span class="p">:</span> <span class="n">user_agent</span><span class="p">}</span>
  354. <span class="n">data</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">parse</span><span class="o">.</span><span class="n">urlencode</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
  355. <span class="n">data</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;ascii&#39;</span><span class="p">)</span>
  356. <span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="n">headers</span><span class="p">)</span>
  357. <span class="k">with</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span> <span class="k">as</span> <span class="n">response</span><span class="p">:</span>
  358. <span class="n">the_page</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
  359. </pre></div>
  360. </div>
  361. <p>The response also has two useful methods. See the section on <a class="reference internal" href="#info-and-geturl">info and geturl</a>
  362. which comes after we have a look at what happens when things go wrong.</p>
  363. </section>
  364. </section>
  365. <section id="handling-exceptions">
  366. <h2>Handling Exceptions<a class="headerlink" href="#handling-exceptions" title="Permalink to this headline">¶</a></h2>
  367. <p><em>urlopen</em> raises <a class="reference internal" href="../library/urllib.error.html#urllib.error.URLError" title="urllib.error.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a> when it cannot handle a response (though as
  368. usual with Python APIs, built-in exceptions such as <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>,
  369. <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> etc. may also be raised).</p>
  370. <p><a class="reference internal" href="../library/urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> is the subclass of <a class="reference internal" href="../library/urllib.error.html#urllib.error.URLError" title="urllib.error.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a> raised in the specific case of
  371. HTTP URLs.</p>
  372. <p>The exception classes are exported from the <a class="reference internal" href="../library/urllib.error.html#module-urllib.error" title="urllib.error: Exception classes raised by urllib.request."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.error</span></code></a> module.</p>
  373. <section id="urlerror">
  374. <h3>URLError<a class="headerlink" href="#urlerror" title="Permalink to this headline">¶</a></h3>
  375. <p>Often, URLError is raised because there is no network connection (no route to
  376. the specified server), or the specified server doesn’t exist. In this case, the
  377. exception raised will have a ‘reason’ attribute, which is a tuple containing an
  378. error code and a text error message.</p>
  379. <p>e.g.</p>
  380. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://www.pretend_server.org&#39;</span><span class="p">)</span>
  381. <span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
  382. <span class="gp">... </span><span class="k">except</span> <span class="n">urllib</span><span class="o">.</span><span class="n">error</span><span class="o">.</span><span class="n">URLError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  383. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">reason</span><span class="p">)</span>
  384. <span class="gp">...</span>
  385. <span class="go">(4, &#39;getaddrinfo failed&#39;)</span>
  386. </pre></div>
  387. </div>
  388. </section>
  389. <section id="httperror">
  390. <h3>HTTPError<a class="headerlink" href="#httperror" title="Permalink to this headline">¶</a></h3>
  391. <p>Every HTTP response from the server contains a numeric “status code”. Sometimes
  392. the status code indicates that the server is unable to fulfil the request. The
  393. default handlers will handle some of these responses for you (for example, if
  394. the response is a “redirection” that requests the client fetch the document from
  395. a different URL, urllib will handle that for you). For those it can’t handle,
  396. urlopen will raise an <a class="reference internal" href="../library/urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a>. Typical errors include ‘404’ (page not
  397. found), ‘403’ (request forbidden), and ‘401’ (authentication required).</p>
  398. <p>See section 10 of <span class="target" id="index-1"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2616.html"><strong>RFC 2616</strong></a> for a reference on all the HTTP error codes.</p>
  399. <p>The <a class="reference internal" href="../library/urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> instance raised will have an integer ‘code’ attribute, which
  400. corresponds to the error sent by the server.</p>
  401. <section id="error-codes">
  402. <h4>Error Codes<a class="headerlink" href="#error-codes" title="Permalink to this headline">¶</a></h4>
  403. <p>Because the default handlers handle redirects (codes in the 300 range), and
  404. codes in the 100–299 range indicate success, you will usually only see error
  405. codes in the 400–599 range.</p>
  406. <p><a class="reference internal" href="../library/http.server.html#http.server.BaseHTTPRequestHandler.responses" title="http.server.BaseHTTPRequestHandler.responses"><code class="xref py py-attr docutils literal notranslate"><span class="pre">http.server.BaseHTTPRequestHandler.responses</span></code></a> is a useful dictionary of
  407. response codes in that shows all the response codes used by <span class="target" id="index-2"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2616.html"><strong>RFC 2616</strong></a>. The
  408. dictionary is reproduced here for convenience</p>
  409. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Table mapping response codes to messages; entries have the</span>
  410. <span class="c1"># form {code: (shortmessage, longmessage)}.</span>
  411. <span class="n">responses</span> <span class="o">=</span> <span class="p">{</span>
  412. <span class="mi">100</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Continue&#39;</span><span class="p">,</span> <span class="s1">&#39;Request received, please continue&#39;</span><span class="p">),</span>
  413. <span class="mi">101</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Switching Protocols&#39;</span><span class="p">,</span>
  414. <span class="s1">&#39;Switching to new protocol; obey Upgrade header&#39;</span><span class="p">),</span>
  415. <span class="mi">200</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;OK&#39;</span><span class="p">,</span> <span class="s1">&#39;Request fulfilled, document follows&#39;</span><span class="p">),</span>
  416. <span class="mi">201</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Created&#39;</span><span class="p">,</span> <span class="s1">&#39;Document created, URL follows&#39;</span><span class="p">),</span>
  417. <span class="mi">202</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Accepted&#39;</span><span class="p">,</span>
  418. <span class="s1">&#39;Request accepted, processing continues off-line&#39;</span><span class="p">),</span>
  419. <span class="mi">203</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Non-Authoritative Information&#39;</span><span class="p">,</span> <span class="s1">&#39;Request fulfilled from cache&#39;</span><span class="p">),</span>
  420. <span class="mi">204</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;No Content&#39;</span><span class="p">,</span> <span class="s1">&#39;Request fulfilled, nothing follows&#39;</span><span class="p">),</span>
  421. <span class="mi">205</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Reset Content&#39;</span><span class="p">,</span> <span class="s1">&#39;Clear input form for further input.&#39;</span><span class="p">),</span>
  422. <span class="mi">206</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Partial Content&#39;</span><span class="p">,</span> <span class="s1">&#39;Partial content follows.&#39;</span><span class="p">),</span>
  423. <span class="mi">300</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Multiple Choices&#39;</span><span class="p">,</span>
  424. <span class="s1">&#39;Object has several resources -- see URI list&#39;</span><span class="p">),</span>
  425. <span class="mi">301</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Moved Permanently&#39;</span><span class="p">,</span> <span class="s1">&#39;Object moved permanently -- see URI list&#39;</span><span class="p">),</span>
  426. <span class="mi">302</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Found&#39;</span><span class="p">,</span> <span class="s1">&#39;Object moved temporarily -- see URI list&#39;</span><span class="p">),</span>
  427. <span class="mi">303</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;See Other&#39;</span><span class="p">,</span> <span class="s1">&#39;Object moved -- see Method and URL list&#39;</span><span class="p">),</span>
  428. <span class="mi">304</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Not Modified&#39;</span><span class="p">,</span>
  429. <span class="s1">&#39;Document has not changed since given time&#39;</span><span class="p">),</span>
  430. <span class="mi">305</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Use Proxy&#39;</span><span class="p">,</span>
  431. <span class="s1">&#39;You must use proxy specified in Location to access this &#39;</span>
  432. <span class="s1">&#39;resource.&#39;</span><span class="p">),</span>
  433. <span class="mi">307</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Temporary Redirect&#39;</span><span class="p">,</span>
  434. <span class="s1">&#39;Object moved temporarily -- see URI list&#39;</span><span class="p">),</span>
  435. <span class="mi">400</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Bad Request&#39;</span><span class="p">,</span>
  436. <span class="s1">&#39;Bad request syntax or unsupported method&#39;</span><span class="p">),</span>
  437. <span class="mi">401</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Unauthorized&#39;</span><span class="p">,</span>
  438. <span class="s1">&#39;No permission -- see authorization schemes&#39;</span><span class="p">),</span>
  439. <span class="mi">402</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Payment Required&#39;</span><span class="p">,</span>
  440. <span class="s1">&#39;No payment -- see charging schemes&#39;</span><span class="p">),</span>
  441. <span class="mi">403</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Forbidden&#39;</span><span class="p">,</span>
  442. <span class="s1">&#39;Request forbidden -- authorization will not help&#39;</span><span class="p">),</span>
  443. <span class="mi">404</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Not Found&#39;</span><span class="p">,</span> <span class="s1">&#39;Nothing matches the given URI&#39;</span><span class="p">),</span>
  444. <span class="mi">405</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Method Not Allowed&#39;</span><span class="p">,</span>
  445. <span class="s1">&#39;Specified method is invalid for this server.&#39;</span><span class="p">),</span>
  446. <span class="mi">406</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Not Acceptable&#39;</span><span class="p">,</span> <span class="s1">&#39;URI not available in preferred format.&#39;</span><span class="p">),</span>
  447. <span class="mi">407</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Proxy Authentication Required&#39;</span><span class="p">,</span> <span class="s1">&#39;You must authenticate with &#39;</span>
  448. <span class="s1">&#39;this proxy before proceeding.&#39;</span><span class="p">),</span>
  449. <span class="mi">408</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Request Timeout&#39;</span><span class="p">,</span> <span class="s1">&#39;Request timed out; try again later.&#39;</span><span class="p">),</span>
  450. <span class="mi">409</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Conflict&#39;</span><span class="p">,</span> <span class="s1">&#39;Request conflict.&#39;</span><span class="p">),</span>
  451. <span class="mi">410</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Gone&#39;</span><span class="p">,</span>
  452. <span class="s1">&#39;URI no longer exists and has been permanently removed.&#39;</span><span class="p">),</span>
  453. <span class="mi">411</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Length Required&#39;</span><span class="p">,</span> <span class="s1">&#39;Client must specify Content-Length.&#39;</span><span class="p">),</span>
  454. <span class="mi">412</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Precondition Failed&#39;</span><span class="p">,</span> <span class="s1">&#39;Precondition in headers is false.&#39;</span><span class="p">),</span>
  455. <span class="mi">413</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Request Entity Too Large&#39;</span><span class="p">,</span> <span class="s1">&#39;Entity is too large.&#39;</span><span class="p">),</span>
  456. <span class="mi">414</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Request-URI Too Long&#39;</span><span class="p">,</span> <span class="s1">&#39;URI is too long.&#39;</span><span class="p">),</span>
  457. <span class="mi">415</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Unsupported Media Type&#39;</span><span class="p">,</span> <span class="s1">&#39;Entity body in unsupported format.&#39;</span><span class="p">),</span>
  458. <span class="mi">416</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Requested Range Not Satisfiable&#39;</span><span class="p">,</span>
  459. <span class="s1">&#39;Cannot satisfy request range.&#39;</span><span class="p">),</span>
  460. <span class="mi">417</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Expectation Failed&#39;</span><span class="p">,</span>
  461. <span class="s1">&#39;Expect condition could not be satisfied.&#39;</span><span class="p">),</span>
  462. <span class="mi">500</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Internal Server Error&#39;</span><span class="p">,</span> <span class="s1">&#39;Server got itself in trouble&#39;</span><span class="p">),</span>
  463. <span class="mi">501</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Not Implemented&#39;</span><span class="p">,</span>
  464. <span class="s1">&#39;Server does not support this operation&#39;</span><span class="p">),</span>
  465. <span class="mi">502</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Bad Gateway&#39;</span><span class="p">,</span> <span class="s1">&#39;Invalid responses from another server/proxy.&#39;</span><span class="p">),</span>
  466. <span class="mi">503</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Service Unavailable&#39;</span><span class="p">,</span>
  467. <span class="s1">&#39;The server cannot process the request due to a high load&#39;</span><span class="p">),</span>
  468. <span class="mi">504</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Gateway Timeout&#39;</span><span class="p">,</span>
  469. <span class="s1">&#39;The gateway server did not receive a timely response&#39;</span><span class="p">),</span>
  470. <span class="mi">505</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;HTTP Version Not Supported&#39;</span><span class="p">,</span> <span class="s1">&#39;Cannot fulfill request.&#39;</span><span class="p">),</span>
  471. <span class="p">}</span>
  472. </pre></div>
  473. </div>
  474. <p>When an error is raised the server responds by returning an HTTP error code
  475. <em>and</em> an error page. You can use the <a class="reference internal" href="../library/urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> instance as a response on the
  476. page returned. This means that as well as the code attribute, it also has read,
  477. geturl, and info, methods as returned by the <code class="docutils literal notranslate"><span class="pre">urllib.response</span></code> module:</p>
  478. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://www.python.org/fish.html&#39;</span><span class="p">)</span>
  479. <span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  480. <span class="gp">... </span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
  481. <span class="gp">... </span><span class="k">except</span> <span class="n">urllib</span><span class="o">.</span><span class="n">error</span><span class="o">.</span><span class="n">HTTPError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  482. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">code</span><span class="p">)</span>
  483. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
  484. <span class="gp">...</span>
  485. <span class="go">404</span>
  486. <span class="go">b&#39;&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;</span>
  487. <span class="go"> &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;\n\n\n&lt;html</span>
  488. <span class="go"> ...</span>
  489. <span class="go"> &lt;title&gt;Page Not Found&lt;/title&gt;\n</span>
  490. <span class="go"> ...</span>
  491. </pre></div>
  492. </div>
  493. </section>
  494. </section>
  495. <section id="wrapping-it-up">
  496. <h3>Wrapping it Up<a class="headerlink" href="#wrapping-it-up" title="Permalink to this headline">¶</a></h3>
  497. <p>So if you want to be prepared for <a class="reference internal" href="../library/urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> <em>or</em> <a class="reference internal" href="../library/urllib.error.html#urllib.error.URLError" title="urllib.error.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a> there are two
  498. basic approaches. I prefer the second approach.</p>
  499. <section id="number-1">
  500. <h4>Number 1<a class="headerlink" href="#number-1" title="Permalink to this headline">¶</a></h4>
  501. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">urllib.request</span> <span class="kn">import</span> <span class="n">Request</span><span class="p">,</span> <span class="n">urlopen</span>
  502. <span class="kn">from</span> <span class="nn">urllib.error</span> <span class="kn">import</span> <span class="n">URLError</span><span class="p">,</span> <span class="n">HTTPError</span>
  503. <span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">someurl</span><span class="p">)</span>
  504. <span class="k">try</span><span class="p">:</span>
  505. <span class="n">response</span> <span class="o">=</span> <span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
  506. <span class="k">except</span> <span class="n">HTTPError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  507. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The server couldn</span><span class="se">\&#39;</span><span class="s1">t fulfill the request.&#39;</span><span class="p">)</span>
  508. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Error code: &#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">code</span><span class="p">)</span>
  509. <span class="k">except</span> <span class="n">URLError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  510. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;We failed to reach a server.&#39;</span><span class="p">)</span>
  511. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Reason: &#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">reason</span><span class="p">)</span>
  512. <span class="k">else</span><span class="p">:</span>
  513. <span class="c1"># everything is fine</span>
  514. </pre></div>
  515. </div>
  516. <div class="admonition note">
  517. <p class="admonition-title">Note</p>
  518. <p>The <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">HTTPError</span></code> <em>must</em> come first, otherwise <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">URLError</span></code>
  519. will <em>also</em> catch an <a class="reference internal" href="../library/urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a>.</p>
  520. </div>
  521. </section>
  522. <section id="number-2">
  523. <h4>Number 2<a class="headerlink" href="#number-2" title="Permalink to this headline">¶</a></h4>
  524. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">urllib.request</span> <span class="kn">import</span> <span class="n">Request</span><span class="p">,</span> <span class="n">urlopen</span>
  525. <span class="kn">from</span> <span class="nn">urllib.error</span> <span class="kn">import</span> <span class="n">URLError</span>
  526. <span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">someurl</span><span class="p">)</span>
  527. <span class="k">try</span><span class="p">:</span>
  528. <span class="n">response</span> <span class="o">=</span> <span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
  529. <span class="k">except</span> <span class="n">URLError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  530. <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">e</span><span class="p">,</span> <span class="s1">&#39;reason&#39;</span><span class="p">):</span>
  531. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;We failed to reach a server.&#39;</span><span class="p">)</span>
  532. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Reason: &#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">reason</span><span class="p">)</span>
  533. <span class="k">elif</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">e</span><span class="p">,</span> <span class="s1">&#39;code&#39;</span><span class="p">):</span>
  534. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The server couldn</span><span class="se">\&#39;</span><span class="s1">t fulfill the request.&#39;</span><span class="p">)</span>
  535. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Error code: &#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">code</span><span class="p">)</span>
  536. <span class="k">else</span><span class="p">:</span>
  537. <span class="c1"># everything is fine</span>
  538. </pre></div>
  539. </div>
  540. </section>
  541. </section>
  542. </section>
  543. <section id="info-and-geturl">
  544. <h2>info and geturl<a class="headerlink" href="#info-and-geturl" title="Permalink to this headline">¶</a></h2>
  545. <p>The response returned by urlopen (or the <a class="reference internal" href="../library/urllib.error.html#urllib.error.HTTPError" title="urllib.error.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> instance) has two
  546. useful methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">geturl()</span></code> and is defined in the module
  547. <a class="reference internal" href="../library/urllib.request.html#module-urllib.response" title="urllib.response: Response classes used by urllib."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.response</span></code></a>..</p>
  548. <p><strong>geturl</strong> - this returns the real URL of the page fetched. This is useful
  549. because <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> (or the opener object used) may have followed a
  550. redirect. The URL of the page fetched may not be the same as the URL requested.</p>
  551. <p><strong>info</strong> - this returns a dictionary-like object that describes the page
  552. fetched, particularly the headers sent by the server. It is currently an
  553. <code class="xref py py-class docutils literal notranslate"><span class="pre">http.client.HTTPMessage</span></code> instance.</p>
  554. <p>Typical headers include ‘Content-length’, ‘Content-type’, and so on. See the
  555. <a class="reference external" href="https://jkorpela.fi/http.html">Quick Reference to HTTP Headers</a>
  556. for a useful listing of HTTP headers with brief explanations of their meaning
  557. and use.</p>
  558. </section>
  559. <section id="openers-and-handlers">
  560. <h2>Openers and Handlers<a class="headerlink" href="#openers-and-handlers" title="Permalink to this headline">¶</a></h2>
  561. <p>When you fetch a URL you use an opener (an instance of the perhaps
  562. confusingly named <a class="reference internal" href="../library/urllib.request.html#urllib.request.OpenerDirector" title="urllib.request.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">urllib.request.OpenerDirector</span></code></a>). Normally we have been using
  563. the default opener - via <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> - but you can create custom
  564. openers. Openers use handlers. All the “heavy lifting” is done by the
  565. handlers. Each handler knows how to open URLs for a particular URL scheme (http,
  566. ftp, etc.), or how to handle an aspect of URL opening, for example HTTP
  567. redirections or HTTP cookies.</p>
  568. <p>You will want to create openers if you want to fetch URLs with specific handlers
  569. installed, for example to get an opener that handles cookies, or to get an
  570. opener that does not handle redirections.</p>
  571. <p>To create an opener, instantiate an <code class="docutils literal notranslate"><span class="pre">OpenerDirector</span></code>, and then call
  572. <code class="docutils literal notranslate"><span class="pre">.add_handler(some_handler_instance)</span></code> repeatedly.</p>
  573. <p>Alternatively, you can use <code class="docutils literal notranslate"><span class="pre">build_opener</span></code>, which is a convenience function for
  574. creating opener objects with a single function call. <code class="docutils literal notranslate"><span class="pre">build_opener</span></code> adds
  575. several handlers by default, but provides a quick way to add more and/or
  576. override the default handlers.</p>
  577. <p>Other sorts of handlers you might want to can handle proxies, authentication,
  578. and other common but slightly specialised situations.</p>
  579. <p><code class="docutils literal notranslate"><span class="pre">install_opener</span></code> can be used to make an <code class="docutils literal notranslate"><span class="pre">opener</span></code> object the (global) default
  580. opener. This means that calls to <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> will use the opener you have
  581. installed.</p>
  582. <p>Opener objects have an <code class="docutils literal notranslate"><span class="pre">open</span></code> method, which can be called directly to fetch
  583. urls in the same way as the <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> function: there’s no need to call
  584. <code class="docutils literal notranslate"><span class="pre">install_opener</span></code>, except as a convenience.</p>
  585. </section>
  586. <section id="id5">
  587. <h2>Basic Authentication<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h2>
  588. <p>To illustrate creating and installing a handler we will use the
  589. <code class="docutils literal notranslate"><span class="pre">HTTPBasicAuthHandler</span></code>. For a more detailed discussion of this subject –
  590. including an explanation of how Basic Authentication works - see the <a class="reference external" href="https://web.archive.org/web/20201215133350/http://www.voidspace.org.uk/python/articles/authentication.shtml">Basic
  591. Authentication Tutorial</a>.</p>
  592. <p>When authentication is required, the server sends a header (as well as the 401
  593. error code) requesting authentication. This specifies the authentication scheme
  594. and a ‘realm’. The header looks like: <code class="docutils literal notranslate"><span class="pre">WWW-Authenticate:</span> <span class="pre">SCHEME</span>
  595. <span class="pre">realm=&quot;REALM&quot;</span></code>.</p>
  596. <p>e.g.</p>
  597. <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WWW-Authenticate: Basic realm=&quot;cPanel Users&quot;
  598. </pre></div>
  599. </div>
  600. <p>The client should then retry the request with the appropriate name and password
  601. for the realm included as a header in the request. This is ‘basic
  602. authentication’. In order to simplify this process we can create an instance of
  603. <code class="docutils literal notranslate"><span class="pre">HTTPBasicAuthHandler</span></code> and an opener to use this handler.</p>
  604. <p>The <code class="docutils literal notranslate"><span class="pre">HTTPBasicAuthHandler</span></code> uses an object called a password manager to handle
  605. the mapping of URLs and realms to passwords and usernames. If you know what the
  606. realm is (from the authentication header sent by the server), then you can use a
  607. <code class="docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code>. Frequently one doesn’t care what the realm is. In that
  608. case, it is convenient to use <code class="docutils literal notranslate"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code>. This allows
  609. you to specify a default username and password for a URL. This will be supplied
  610. in the absence of you providing an alternative combination for a specific
  611. realm. We indicate this by providing <code class="docutils literal notranslate"><span class="pre">None</span></code> as the realm argument to the
  612. <code class="docutils literal notranslate"><span class="pre">add_password</span></code> method.</p>
  613. <p>The top-level URL is the first URL that requires authentication. URLs “deeper”
  614. than the URL you pass to .add_password() will also match.</p>
  615. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># create a password manager</span>
  616. <span class="n">password_mgr</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">HTTPPasswordMgrWithDefaultRealm</span><span class="p">()</span>
  617. <span class="c1"># Add the username and password.</span>
  618. <span class="c1"># If we knew the realm, we could use it instead of None.</span>
  619. <span class="n">top_level_url</span> <span class="o">=</span> <span class="s2">&quot;http://example.com/foo/&quot;</span>
  620. <span class="n">password_mgr</span><span class="o">.</span><span class="n">add_password</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="n">top_level_url</span><span class="p">,</span> <span class="n">username</span><span class="p">,</span> <span class="n">password</span><span class="p">)</span>
  621. <span class="n">handler</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">HTTPBasicAuthHandler</span><span class="p">(</span><span class="n">password_mgr</span><span class="p">)</span>
  622. <span class="c1"># create &quot;opener&quot; (OpenerDirector instance)</span>
  623. <span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>
  624. <span class="c1"># use the opener to fetch a URL</span>
  625. <span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">a_url</span><span class="p">)</span>
  626. <span class="c1"># Install the opener.</span>
  627. <span class="c1"># Now all calls to urllib.request.urlopen use our opener.</span>
  628. <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">install_opener</span><span class="p">(</span><span class="n">opener</span><span class="p">)</span>
  629. </pre></div>
  630. </div>
  631. <div class="admonition note">
  632. <p class="admonition-title">Note</p>
  633. <p>In the above example we only supplied our <code class="docutils literal notranslate"><span class="pre">HTTPBasicAuthHandler</span></code> to
  634. <code class="docutils literal notranslate"><span class="pre">build_opener</span></code>. By default openers have the handlers for normal situations
  635. – <code class="docutils literal notranslate"><span class="pre">ProxyHandler</span></code> (if a proxy setting such as an <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">http_proxy</span></code>
  636. environment variable is set), <code class="docutils literal notranslate"><span class="pre">UnknownHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">HTTPHandler</span></code>,
  637. <code class="docutils literal notranslate"><span class="pre">HTTPDefaultErrorHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">HTTPRedirectHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">FTPHandler</span></code>,
  638. <code class="docutils literal notranslate"><span class="pre">FileHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">DataHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">HTTPErrorProcessor</span></code>.</p>
  639. </div>
  640. <p><code class="docutils literal notranslate"><span class="pre">top_level_url</span></code> is in fact <em>either</em> a full URL (including the ‘http:’ scheme
  641. component and the hostname and optionally the port number)
  642. e.g. <code class="docutils literal notranslate"><span class="pre">&quot;http://example.com/&quot;</span></code> <em>or</em> an “authority” (i.e. the hostname,
  643. optionally including the port number) e.g. <code class="docutils literal notranslate"><span class="pre">&quot;example.com&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;example.com:8080&quot;</span></code>
  644. (the latter example includes a port number). The authority, if present, must
  645. NOT contain the “userinfo” component - for example <code class="docutils literal notranslate"><span class="pre">&quot;joe:password&#64;example.com&quot;</span></code> is
  646. not correct.</p>
  647. </section>
  648. <section id="proxies">
  649. <h2>Proxies<a class="headerlink" href="#proxies" title="Permalink to this headline">¶</a></h2>
  650. <p><strong>urllib</strong> will auto-detect your proxy settings and use those. This is through
  651. the <code class="docutils literal notranslate"><span class="pre">ProxyHandler</span></code>, which is part of the normal handler chain when a proxy
  652. setting is detected. Normally that’s a good thing, but there are occasions
  653. when it may not be helpful <a class="footnote-reference brackets" href="#id12" id="id6">5</a>. One way to do this is to setup our own
  654. <code class="docutils literal notranslate"><span class="pre">ProxyHandler</span></code>, with no proxies defined. This is done using similar steps to
  655. setting up a <a class="reference external" href="https://web.archive.org/web/20201215133350/http://www.voidspace.org.uk/python/articles/authentication.shtml">Basic Authentication</a> handler:</p>
  656. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">proxy_support</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">ProxyHandler</span><span class="p">({})</span>
  657. <span class="gp">&gt;&gt;&gt; </span><span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">proxy_support</span><span class="p">)</span>
  658. <span class="gp">&gt;&gt;&gt; </span><span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">install_opener</span><span class="p">(</span><span class="n">opener</span><span class="p">)</span>
  659. </pre></div>
  660. </div>
  661. <div class="admonition note">
  662. <p class="admonition-title">Note</p>
  663. <p>Currently <code class="docutils literal notranslate"><span class="pre">urllib.request</span></code> <em>does not</em> support fetching of <code class="docutils literal notranslate"><span class="pre">https</span></code> locations
  664. through a proxy. However, this can be enabled by extending urllib.request as
  665. shown in the recipe <a class="footnote-reference brackets" href="#id13" id="id7">6</a>.</p>
  666. </div>
  667. <div class="admonition note">
  668. <p class="admonition-title">Note</p>
  669. <p><code class="docutils literal notranslate"><span class="pre">HTTP_PROXY</span></code> will be ignored if a variable <code class="docutils literal notranslate"><span class="pre">REQUEST_METHOD</span></code> is set; see
  670. the documentation on <a class="reference internal" href="../library/urllib.request.html#urllib.request.getproxies" title="urllib.request.getproxies"><code class="xref py py-func docutils literal notranslate"><span class="pre">getproxies()</span></code></a>.</p>
  671. </div>
  672. </section>
  673. <section id="sockets-and-layers">
  674. <h2>Sockets and Layers<a class="headerlink" href="#sockets-and-layers" title="Permalink to this headline">¶</a></h2>
  675. <p>The Python support for fetching resources from the web is layered. urllib uses
  676. the <a class="reference internal" href="../library/http.client.html#module-http.client" title="http.client: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">http.client</span></code></a> library, which in turn uses the socket library.</p>
  677. <p>As of Python 2.3 you can specify how long a socket should wait for a response
  678. before timing out. This can be useful in applications which have to fetch web
  679. pages. By default the socket module has <em>no timeout</em> and can hang. Currently,
  680. the socket timeout is not exposed at the http.client or urllib.request levels.
  681. However, you can set the default timeout globally for all sockets using</p>
  682. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span>
  683. <span class="kn">import</span> <span class="nn">urllib.request</span>
  684. <span class="c1"># timeout in seconds</span>
  685. <span class="n">timeout</span> <span class="o">=</span> <span class="mi">10</span>
  686. <span class="n">socket</span><span class="o">.</span><span class="n">setdefaulttimeout</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span>
  687. <span class="c1"># this call to urllib.request.urlopen now uses the default timeout</span>
  688. <span class="c1"># we have set in the socket module</span>
  689. <span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://www.voidspace.org.uk&#39;</span><span class="p">)</span>
  690. <span class="n">response</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
  691. </pre></div>
  692. </div>
  693. </section>
  694. <hr class="docutils" />
  695. <section id="footnotes">
  696. <h2>Footnotes<a class="headerlink" href="#footnotes" title="Permalink to this headline">¶</a></h2>
  697. <p>This document was reviewed and revised by John Lee.</p>
  698. <dl class="footnote brackets">
  699. <dt class="label" id="id8"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
  700. <dd><p>Google for example.</p>
  701. </dd>
  702. <dt class="label" id="id9"><span class="brackets"><a class="fn-backref" href="#id2">2</a></span></dt>
  703. <dd><p>Browser sniffing is a very bad practice for website design - building
  704. sites using web standards is much more sensible. Unfortunately a lot of
  705. sites still send different versions to different browsers.</p>
  706. </dd>
  707. <dt class="label" id="id10"><span class="brackets"><a class="fn-backref" href="#id3">3</a></span></dt>
  708. <dd><p>The user agent for MSIE 6 is
  709. <em>‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)’</em></p>
  710. </dd>
  711. <dt class="label" id="id11"><span class="brackets"><a class="fn-backref" href="#id4">4</a></span></dt>
  712. <dd><p>For details of more HTTP request headers, see
  713. <a class="reference external" href="https://jkorpela.fi/http.html">Quick Reference to HTTP Headers</a>.</p>
  714. </dd>
  715. <dt class="label" id="id12"><span class="brackets"><a class="fn-backref" href="#id6">5</a></span></dt>
  716. <dd><p>In my case I have to use a proxy to access the internet at work. If you
  717. attempt to fetch <em>localhost</em> URLs through this proxy it blocks them. IE
  718. is set to use the proxy, which urllib picks up on. In order to test
  719. scripts with a localhost server, I have to prevent urllib from using
  720. the proxy.</p>
  721. </dd>
  722. <dt class="label" id="id13"><span class="brackets"><a class="fn-backref" href="#id7">6</a></span></dt>
  723. <dd><p>urllib opener for SSL proxy (CONNECT method): <a class="reference external" href="https://code.activestate.com/recipes/456195/">ASPN Cookbook Recipe</a>.</p>
  724. </dd>
  725. </dl>
  726. </section>
  727. </section>
  728. <div class="clearer"></div>
  729. </div>
  730. </div>
  731. </div>
  732. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  733. <div class="sphinxsidebarwrapper">
  734. <div>
  735. <h3><a href="../contents.html">Table of Contents</a></h3>
  736. <ul>
  737. <li><a class="reference internal" href="#">HOWTO Fetch Internet Resources Using The urllib Package</a><ul>
  738. <li><a class="reference internal" href="#introduction">Introduction</a></li>
  739. <li><a class="reference internal" href="#fetching-urls">Fetching URLs</a><ul>
  740. <li><a class="reference internal" href="#data">Data</a></li>
  741. <li><a class="reference internal" href="#headers">Headers</a></li>
  742. </ul>
  743. </li>
  744. <li><a class="reference internal" href="#handling-exceptions">Handling Exceptions</a><ul>
  745. <li><a class="reference internal" href="#urlerror">URLError</a></li>
  746. <li><a class="reference internal" href="#httperror">HTTPError</a><ul>
  747. <li><a class="reference internal" href="#error-codes">Error Codes</a></li>
  748. </ul>
  749. </li>
  750. <li><a class="reference internal" href="#wrapping-it-up">Wrapping it Up</a><ul>
  751. <li><a class="reference internal" href="#number-1">Number 1</a></li>
  752. <li><a class="reference internal" href="#number-2">Number 2</a></li>
  753. </ul>
  754. </li>
  755. </ul>
  756. </li>
  757. <li><a class="reference internal" href="#info-and-geturl">info and geturl</a></li>
  758. <li><a class="reference internal" href="#openers-and-handlers">Openers and Handlers</a></li>
  759. <li><a class="reference internal" href="#id5">Basic Authentication</a></li>
  760. <li><a class="reference internal" href="#proxies">Proxies</a></li>
  761. <li><a class="reference internal" href="#sockets-and-layers">Sockets and Layers</a></li>
  762. <li><a class="reference internal" href="#footnotes">Footnotes</a></li>
  763. </ul>
  764. </li>
  765. </ul>
  766. </div>
  767. <div>
  768. <h4>Previous topic</h4>
  769. <p class="topless"><a href="unicode.html"
  770. title="previous chapter">Unicode HOWTO</a></p>
  771. </div>
  772. <div>
  773. <h4>Next topic</h4>
  774. <p class="topless"><a href="argparse.html"
  775. title="next chapter">Argparse Tutorial</a></p>
  776. </div>
  777. <div role="note" aria-label="source link">
  778. <h3>This Page</h3>
  779. <ul class="this-page-menu">
  780. <li><a href="../bugs.html">Report a Bug</a></li>
  781. <li>
  782. <a href="https://github.com/python/cpython/blob/main/Doc/howto/urllib2.rst"
  783. rel="nofollow">Show Source
  784. </a>
  785. </li>
  786. </ul>
  787. </div>
  788. </div>
  789. </div>
  790. <div class="clearer"></div>
  791. </div>
  792. <div class="related" role="navigation" aria-label="related navigation">
  793. <h3>Navigation</h3>
  794. <ul>
  795. <li class="right" style="margin-right: 10px">
  796. <a href="../genindex.html" title="General Index"
  797. >index</a></li>
  798. <li class="right" >
  799. <a href="../py-modindex.html" title="Python Module Index"
  800. >modules</a> |</li>
  801. <li class="right" >
  802. <a href="argparse.html" title="Argparse Tutorial"
  803. >next</a> |</li>
  804. <li class="right" >
  805. <a href="unicode.html" title="Unicode HOWTO"
  806. >previous</a> |</li>
  807. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  808. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  809. <li class="switchers">
  810. <div class="language_switcher_placeholder"></div>
  811. <div class="version_switcher_placeholder"></div>
  812. </li>
  813. <li>
  814. </li>
  815. <li id="cpython-language-and-version">
  816. <a href="../index.html">3.12.0 Documentation</a> &#187;
  817. </li>
  818. <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li>
  819. <li class="nav-item nav-item-this"><a href="">HOWTO Fetch Internet Resources Using The urllib Package</a></li>
  820. <li class="right">
  821. <div class="inline-search" role="search">
  822. <form class="inline-search" action="../search.html" method="get">
  823. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  824. <input type="submit" value="Go" />
  825. </form>
  826. </div>
  827. |
  828. </li>
  829. <li class="right">
  830. <label class="theme-selector-label">
  831. Theme
  832. <select class="theme-selector" oninput="activateTheme(this.value)">
  833. <option value="auto" selected>Auto</option>
  834. <option value="light">Light</option>
  835. <option value="dark">Dark</option>
  836. </select>
  837. </label> |</li>
  838. </ul>
  839. </div>
  840. <div class="footer">
  841. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  842. <br />
  843. This page is licensed under the Python Software Foundation License Version 2.
  844. <br />
  845. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  846. <br />
  847. See <a href="/license.html">History and License</a> for more information.<br />
  848. <br />
  849. The Python Software Foundation is a non-profit corporation.
  850. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  851. <br />
  852. <br />
  853. Last updated on Oct 02, 2023.
  854. <a href="/bugs.html">Found a bug</a>?
  855. <br />
  856. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  857. </div>
  858. </body>
  859. </html>