urllib2.md
1> **Источник:** https://python-all.ru/3.1/howto/urllib2.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# HOWTO получение интернет-ресурсов с помощью пакета urllib89| Автор: | [Michael Foord](https://python-all.ru/3.1/howto/urllib2.html) |10| --- | --- |1112> **Примечание**13>14> Существует французский перевод более ранней версии этого руководства, доступный по адресу [urllib2 - Le Manuel manquant](https://python-all.ru/3.1/howto/urllib2.html).1516## Введение1718Связанные статьи1920Возможно, вам также будет полезна следующая статья о получении веб-ресурсов с помощью Python:2122- [Базовая аутентификация](https://python-all.ru/3.1/howto/urllib2.html)2324 > Учебник по *базовой аутентификации* с примерами на Python.2526**urllib.request** – это модуль [Python](https://python-all.ru/3.1/howto/urllib2.html) для получения URL (Uniform Resource Locators). Он предоставляет очень простой интерфейс в виде функции *urlopen*. Эта функция может получать URL с использованием различных протоколов. Также он предоставляет немного более сложный интерфейс для обработки типичных ситуаций, таких как базовая аутентификация, куки, прокси и т.д. Эти возможности обеспечиваются объектами, называемыми обработчиками и открывателями.2728urllib.request поддерживает получение URL-адресов для многих «схем URL» (определяемых строкой перед «:» в URL – например, «ftp» – это схема URL «[ftp://python.org/](ftp://python.org/)») с использованием соответствующих сетевых протоколов (например, FTP, HTTP). Это руководство посвящено наиболее распространённому случаю – HTTP.2930For 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**](https://python-all.ru/3.1/howto/urllib2.html). This is a technical document and not intended to be easy to read. This HOWTO aims to illustrate using *urllib*, with enough detail about HTTP to help you through. It is not intended to replace the [`urllib.request`](https://python-all.ru/3.1/library/urllib.request.html#module-urllib.request) docs, but is supplementary to them.3132## Загрузка URL3334Простейший способ использования urllib.request выглядит так:3536```python37import urllib.request38response = urllib.request.urlopen('http://python.org/')39html = response.read()40```4142Многие случаи использования urllib будут настолько же простыми (обратите внимание, что вместо URL с ‘http:’ мы могли бы использовать URL, начинающийся с ‘ftp:’, ‘file:’ и т.д.). Однако цель данного руководства – объяснить более сложные случаи, сосредоточившись на HTTP.4344HTTP is based on requests and responses - the client makes requests and servers send responses. urllib.request mirrors this with a `Request` object which represents 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:4546```python47import urllib.request4849req = urllib.request.Request('http://www.voidspace.org.uk')50response = urllib.request.urlopen(req)51the_page = response.read()52```5354Обратите внимание, что urllib.request использует тот же интерфейс Request для обработки всех схем URL. Например, можно сделать FTP-запрос так:5556```python57req = urllib.request.Request('ftp://example.com/')58```5960В случае HTTP объекты Request позволяют сделать ещё две вещи: во-первых, можно передать данные для отправки на сервер. Во-вторых, можно передать серверу дополнительную информацию («метаданные») *о* данных или о самом запросе – эта информация отправляется в виде HTTP-заголовков. Рассмотрим каждую из них по очереди.6162### Данные6364Иногда требуется отправить данные на URL (часто URL ссылается на CGI-скрипт (Common Gateway Interface) [\[1\]](https://python-all.ru/3.1/howto/urllib2.html#id9) или другое веб-приложение). В HTTP это обычно делается с помощью так называемого **POST**-запроса. Именно так ваш браузер отправляет заполненную HTML-форму. Не все POST-запросы должны приходить из форм: можно использовать POST для передачи произвольных данных в собственное приложение. В типичном случае HTML-форм данные необходимо закодировать стандартным способом, а затем передать в объект Request в качестве аргумента `data`. Кодирование выполняется с помощью функции из библиотеки [`urllib.parse`](https://python-all.ru/3.1/library/urllib.parse.html#module-urllib.parse).6566```python67import urllib.parse68import urllib.request6970url = 'http://www.someserver.com/cgi-bin/register.cgi'71values = {'name' : 'Michael Foord',72 'location' : 'Northampton',73 'language' : 'Python' }7475data = urllib.parse.urlencode(values)76req = urllib.request.Request(url, data)77response = urllib.request.urlopen(req)78the_page = response.read()79```8081Обратите внимание, что иногда требуются другие кодировки (например, для загрузки файлов из HTML-форм – подробнее см. [Спецификацию HTML, раздел «Отправка формы»](https://python-all.ru/3.1/howto/urllib2.html)).8283If you do not pass the `data` argument, urllib uses a **GET** request. One 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.8485Это делается следующим образом:8687```python88>>> import urllib.request89>>> import urllib.parse90>>> data = {}91>>> data['name'] = 'Somebody Here'92>>> data['location'] = 'Northampton'93>>> data['language'] = 'Python'94>>> url_values = urllib.parse.urlencode(data)95>>> print(url_values)96name=Somebody+Here&language=Python&location=Northampton97>>> url = 'http://www.example.com/example.cgi'98>>> full_url = url + '?' + url_values99>>> data = urllib.request.open(full_url)100```101102Обратите внимание, что полный URL создаётся добавлением `?` к URL, после которого следуют закодированные значения.103104### Заголовки105106Здесь будет рассмотрен один конкретный HTTP-заголовок, чтобы проиллюстрировать, как добавлять заголовки в HTTP-запросы.107108Некоторым сайтам [\[2\]](https://python-all.ru/3.1/howto/urllib2.html#id10) не нравится, когда их просматривают программы, или они отправляют разные версии разным браузерам [\[3\]](https://python-all.ru/3.1/howto/urllib2.html#id11). По умолчанию urllib идентифицирует себя как `Python-urllib/x.y` (где `x` и `y` – это номера старшей и младшей версии релиза Python, например `Python-urllib/2.5`), что может сбивать сайт с толку или просто не работать. Способ, которым браузер идентифицирует себя, – это заголовок `User-Agent` [\[4\]](https://python-all.ru/3.1/howto/urllib2.html#id12). При создании объекта Request можно передать словарь заголовков. В следующем примере выполняется тот же запрос, что и выше, но идентифицируется как версия Internet Explorer [\[5\]](https://python-all.ru/3.1/howto/urllib2.html#id13).109110```python111import urllib.parse112import urllib.request113114url = 'http://www.someserver.com/cgi-bin/register.cgi'115user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'116values = {'name' : 'Michael Foord',117 'location' : 'Northampton',118 'language' : 'Python' }119headers = { 'User-Agent' : user_agent }120121data = urllib.parse.urlencode(values)122req = urllib.request.Request(url, data, headers)123response = urllib.request.urlopen(req)124the_page = response.read()125```126127Ответ также имеет два полезных метода. См. раздел [info и geturl](https://python-all.ru/3.1/howto/urllib2.html#info-and-geturl), который следует после того, как мы рассмотрим, что происходит, когда что-то идёт не так.128129## Обработка исключений130131*urlopen* raises `URLError` when it cannot handle a response (though as usual with Python APIs, built-in exceptions such as [`ValueError`](https://python-all.ru/3.1/library/exceptions.html#ValueError), [`TypeError`](https://python-all.ru/3.1/library/exceptions.html#TypeError) etc. may also be raised).132133`HTTPError` is the subclass of `URLError` raised in the specific case of HTTP URLs.134135The exception classes are exported from the [`urllib.error`](https://python-all.ru/3.1/library/urllib.error.html#module-urllib.error) module.136137### URLError138139Часто URLError возникает из-за отсутствия сетевого соединения (нет маршрута к указанному серверу) или потому что указанный сервер не существует. В этом случае возбуждённое исключение будет иметь атрибут 'reason', который представляет собой кортеж, содержащий код ошибки и текстовое сообщение об ошибке.140141например142143```python144>>> req = urllib.request.Request('http://www.pretend_server.org')145>>> try: urllib.request.urlopen(req)146>>> except urllib.error.URLError as e:147>>> print(e.reason)148>>>149(4, 'getaddrinfo failed')150```151152### HTTPError153154Every 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 a different URL, urllib will handle that for you). For those it can’t handle, urlopen will raise an `HTTPError`. Typical errors include ‘404’ (page not found), ‘403’ (request forbidden), and ‘401’ (authentication required).155156Все коды ошибок HTTP перечислены в разделе 10 документа RFC 2616.157158The `HTTPError` instance raised will have an integer ‘code’ attribute, which corresponds to the error sent by the server.159160#### Коды ошибок161162Поскольку обработчики по умолчанию обрабатывают перенаправления (коды в диапазоне 300), а коды в диапазоне 100-299 указывают на успех, вы обычно будете видеть коды ошибок только в диапазоне 400-599.163164[`http.server.BaseHTTPRequestHandler.responses`](https://python-all.ru/3.1/library/http.server.html#http.server.BaseHTTPRequestHandler.responses) is a useful dictionary of response codes in that shows all the response codes used by RFC 2616. The dictionary is reproduced here for convenience165166```python167# Таблица, сопоставляющая коды ответов с сообщениями; записи имеют168# вид {code: (shortmessage, longmessage)}.169responses = {170 100: ('Continue', 'Request received, please continue'),171 101: ('Switching Protocols',172 'Switching to new protocol; obey Upgrade header'),173174 200: ('OK', 'Request fulfilled, document follows'),175 201: ('Created', 'Document created, URL follows'),176 202: ('Accepted',177 'Request accepted, processing continues off-line'),178 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),179 204: ('No Content', 'Request fulfilled, nothing follows'),180 205: ('Reset Content', 'Clear input form for further input.'),181 206: ('Partial Content', 'Partial content follows.'),182183 300: ('Multiple Choices',184 'Object has several resources -- see URI list'),185 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),186 302: ('Found', 'Object moved temporarily -- see URI list'),187 303: ('See Other', 'Object moved -- see Method and URL list'),188 304: ('Not Modified',189 'Document has not changed since given time'),190 305: ('Use Proxy',191 'You must use proxy specified in Location to access this '192 'resource.'),193 307: ('Temporary Redirect',194 'Object moved temporarily -- see URI list'),195196 400: ('Bad Request',197 'Bad request syntax or unsupported method'),198 401: ('Unauthorized',199 'No permission -- see authorization schemes'),200 402: ('Payment Required',201 'No payment -- see charging schemes'),202 403: ('Forbidden',203 'Request forbidden -- authorization will not help'),204 404: ('Not Found', 'Nothing matches the given URI'),205 405: ('Method Not Allowed',206 'Specified method is invalid for this server.'),207 406: ('Not Acceptable', 'URI not available in preferred format.'),208 407: ('Proxy Authentication Required', 'You must authenticate with '209 'this proxy before proceeding.'),210 408: ('Request Timeout', 'Request timed out; try again later.'),211 409: ('Conflict', 'Request conflict.'),212 410: ('Gone',213 'URI no longer exists and has been permanently removed.'),214 411: ('Length Required', 'Client must specify Content-Length.'),215 412: ('Precondition Failed', 'Precondition in headers is false.'),216 413: ('Request Entity Too Large', 'Entity is too large.'),217 414: ('Request-URI Too Long', 'URI is too long.'),218 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),219 416: ('Requested Range Not Satisfiable',220 'Cannot satisfy request range.'),221 417: ('Expectation Failed',222 'Expect condition could not be satisfied.'),223224 500: ('Internal Server Error', 'Server got itself in trouble'),225 501: ('Not Implemented',226 'Server does not support this operation'),227 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),228 503: ('Service Unavailable',229 'The server cannot process the request due to a high load'),230 504: ('Gateway Timeout',231 'The gateway server did not receive a timely response'),232 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),233 }234```235236When an error is raised the server responds by returning an HTTP error code *and* an error page. You can use the `HTTPError` instance as a response on the page returned. This means that as well as the code attribute, it also has read, geturl, and info, methods as returned by the `urllib.response` module:237238```python239>>> req = urllib.request.Request('http://www.python.org/fish.html')240>>> try:241>>> urllib.request.urlopen(req)242>>> except urllib.error.HTTPError as e:243>>> print(e.code)244>>> print(e.read())245>>>246404247<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"248 "http://www.w3.org/TR/html4/loose.dtd">249<?xml-stylesheet href="./css/ht2html.css"250 type="text/css"?>251<html><head><title>Error 404: File Not Found</title>252...... etc...253```254255### Резюме256257So if you want to be prepared for `HTTPError` *or* `URLError` there are two basic approaches. I prefer the second approach.258259#### Способ 1260261```python262from urllib.request import Request, urlopen263from urllib.error import URLError, HTTPError264req = Request(someurl)265try:266 response = urlopen(req)267except HTTPError as e:268 print('The server couldn\'t fulfill the request.')269 print('Error code: ', e.code)270except URLError as e:271 print('We failed to reach a server.')272 print('Reason: ', e.reason)273else:274 # всё в порядке275```276277> **Примечание**278>279> The `except HTTPError` *must* come first, otherwise `except URLError` will *also* catch an `HTTPError`.280281#### Способ 2282283```python284from urllib.request import Request, urlopen285from urllib.error import URLError286req = Request(someurl)287try:288 response = urlopen(req)289except URLError as e:290 if hasattr(e, 'reason'):291 print('We failed to reach a server.')292 print('Reason: ', e.reason)293 elif hasattr(e, 'code'):294 print('The server couldn\'t fulfill the request.')295 print('Error code: ', e.code)296else:297 # всё в порядке298```299300## info и geturl301302The response returned by urlopen (or the `HTTPError` instance) has two useful methods `info()` and `geturl()` and is defined in the module [`urllib.response`](https://python-all.ru/3.1/library/urllib.request.html#module-urllib.response)..303304**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.305306**info** - this returns a dictionary-like object that describes the page fetched, particularly the headers sent by the server. It is currently an `http.client.HTTPMessage` instance.307308Типичные заголовки включают ‘Content-length’, ‘Content-type’ и т.д. Смотрите [Краткий справочник HTTP-заголовков](https://python-all.ru/3.1/howto/urllib2.html) для полезного списка HTTP-заголовков с краткими пояснениями их значения и использования.309310## Открыватели и обработчики311312When you fetch a URL you use an opener (an instance of the perhaps confusingly-named [`urllib.request.OpenerDirector`](https://python-all.ru/3.1/library/urllib.request.html#urllib.request.OpenerDirector)). Normally we have been using 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.313314Стоит создавать собственные opener'ы, если нужно получать URL с установленными определёнными обработчиками, например чтобы получить opener, обрабатывающий cookies, или opener, не обрабатывающий перенаправления.315316To create an opener, instantiate an `OpenerDirector`, and then call `.add_handler(some_handler_instance)` repeatedly.317318Alternatively, 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.319320Другие типы обработчиков могут обрабатывать прокси, аутентификацию и другие распространённые, но слегка специализированные ситуации.321322`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.323324Opener 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.325326## Базовая аутентификация327328To 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](https://python-all.ru/3.1/howto/urllib2.html).329330Когда требуется аутентификация, сервер отправляет заголовок (а также код ошибки 401), запрашивающий аутентификацию. В нём указывается схема аутентификации и «realm» (область). Заголовок выглядит так: `Www-authenticate: SCHEME realm="REALM"`.331332например333334```python335Www-authenticate: Basic realm="cPanel Users"336```337338Затем клиент должен повторить запрос, указав соответствующие имя и пароль для области (realm) в качестве заголовка запроса. Это называется «базовая аутентификация». Чтобы упростить этот процесс, можно создать экземпляр `HTTPBasicAuthHandler` и opener для использования этого обработчика.339340`HTTPBasicAuthHandler` использует объект, называемый менеджером паролей, для управления сопоставлением URL и областей (realm) с паролями и именами пользователей. Если известно, что представляет собой область (из заголовка аутентификации, отправленного сервером), то можно использовать `HTTPPasswordMgr`. Часто область не имеет значения. В таком случае удобно использовать `HTTPPasswordMgrWithDefaultRealm`. Это позволяет указать имя пользователя и пароль по умолчанию для URL. Они будут использоваться при отсутствии альтернативной комбинации для конкретной области. Для этого нужно передать `None` в качестве аргумента realm методу `add_password`.341342URL верхнего уровня – это первый URL, требующий аутентификации. URL «глубже», чем переданный в .add\_password(), также будут соответствовать.343344```python345# создать менеджер паролей346password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()347348# Добавить имя пользователя и пароль.349# Если бы мы знали realm, мы могли бы использовать его вместо None.350top_level_url = "http://example.com/foo/"351password_mgr.add_password(None, top_level_url, username, password)352353handler = urllib.request.HTTPBasicAuthHandler(password_mgr)354355# создать "opener" (экземпляр OpenerDirector)356opener = urllib.request.build_opener(handler)357358# использовать opener для получения URL359opener.open(a_url)360361# Установить opener.362# Теперь все вызовы urllib.request.urlopen будут использовать наш opener.363urllib.request.install_opener(opener)364```365366> **Примечание**367>368> В приведенном выше примере мы передали только `HTTPBasicAuthHandler` в `build_opener`. По умолчанию открыватели содержат обработчики для обычных ситуаций: `ProxyHandler`, `UnknownHandler`, `HTTPHandler`, `HTTPDefaultErrorHandler`, `HTTPRedirectHandler`, `FTPHandler`, `FileHandler`, `HTTPErrorProcessor`.369370`top_level_url` на самом деле *может быть* полным URL (включая схему 'http:' и имя хоста, а также, опционально, номер порта), например, “[http://example.com/](https://python-all.ru/3.1/howto/urllib2.html)” *или* «authority» (т.е. имя хоста, опционально включая номер порта), например, “example.com” или “example.com:8080” (последний пример включает номер порта). Authority, если присутствует, не должен содержать компонент «userinfo» – например, “joe@password:example.com” неверен.371372## Прокси373374**urllib** автоматически определит настройки прокси и будет их использовать. Это происходит через `ProxyHandler`, который является частью обычной цепочки обработчиков. Обычно это хорошо, но бывают случаи, когда это может быть нежелательно [\[6\]](https://python-all.ru/3.1/howto/urllib2.html#id14). Один из способов – настроить собственный `ProxyHandler` без определения прокси. Это делается с помощью шагов, аналогичных настройке обработчика [Basic Authentication](https://python-all.ru/3.1/howto/urllib2.html):375376```python377>>> proxy_support = urllib.request.ProxyHandler({})378>>> opener = urllib.request.build_opener(proxy_support)379>>> urllib.request.install_opener(opener)380```381382> **Примечание**383>384> В настоящее время `urllib.request` *не поддерживает* получение `https`-ресурсов через прокси. Однако эту возможность можно включить, расширив urllib.request, как показано в рецепте [\[7\]](https://python-all.ru/3.1/howto/urllib2.html#id15).385386## Сокеты и уровни387388Поддержка Python для получения ресурсов из сети является многоуровневой. urllib использует библиотеку [`http.client`](https://python-all.ru/3.1/library/http.client.html#module-http.client), которая, в свою очередь, использует библиотеку socket.389390Начиная с Python 2.3 можно указать, как долго сокет должен ждать ответа до истечения тайм-аута. Это может быть полезно в приложениях, которым приходится получать веб-страницы. По умолчанию модуль socket не имеет *тайм-аута* и может зависнуть. В настоящее время тайм-аут сокета не доступен на уровнях http.client или urllib.request. Однако можно установить глобальный тайм-аут по умолчанию для всех сокетов с помощью391392```python393import socket394import urllib.request395396# тайм-аут в секундах397timeout = 10398socket.setdefaulttimeout(timeout)399400# этот вызов urllib.request.urlopen теперь использует тайм-аут по умолчанию401# который мы установили в модуле socket402req = urllib.request.Request('http://www.voidspace.org.uk')403response = urllib.request.urlopen(req)404```405406---407408## Примечания409410Этот документ был проверен и доработан Джоном Ли.411412| [\[1\]](https://python-all.ru/3.1/howto/urllib2.html#id1) | Введение в протокол CGI см. в [Writing Web Applications in Python](https://python-all.ru/3.1/howto/urllib2.html). |413| --- | --- |414415| [\[2\]](https://python-all.ru/3.1/howto/urllib2.html#id2) | Например, Google. *Правильный* способ использовать Google из программы – это, конечно, использовать [PyGoogle](https://python-all.ru/3.1/howto/urllib2.html). См. [Voidspace Google](https://python-all.ru/3.1/howto/urllib2.html) для примеров использования Google API. |416| --- | --- |417418| [\[3\]](https://python-all.ru/3.1/howto/urllib2.html#id3) | Определение браузера (browser sniffing) – очень плохая практика при проектировании веб-сайтов; гораздо разумнее создавать сайты с использованием веб-стандартов. К сожалению, многие сайты до сих пор отправляют разные версии разным браузерам. |419| --- | --- |420421| [\[4\]](https://python-all.ru/3.1/howto/urllib2.html#id4) | Пользовательский агент для MSIE 6 – *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'* |422| --- | --- |423424| [\[5\]](https://python-all.ru/3.1/howto/urllib2.html#id5) | Подробнее о HTTP-заголовках запросов см. [Quick Reference to HTTP Headers](https://python-all.ru/3.1/howto/urllib2.html). |425| --- | --- |426427| [\[6\]](https://python-all.ru/3.1/howto/urllib2.html#id7) | В моём случае на работе приходится использовать прокси для доступа в интернет. Если через этот прокси пытаться получить *localhost*-URL, он их блокирует. В IE настроено использование прокси, и urllib это подхватывает. Чтобы тестировать скрипты с локальным сервером, приходится запрещать urllib использовать прокси. |428| --- | --- |429430| [\[7\]](https://python-all.ru/3.1/howto/urllib2.html#id8) | Открыватель urllib для SSL-прокси (метод CONNECT): [ASPN Cookbook Recipe](https://python-all.ru/3.1/howto/urllib2.html). |431| --- | --- |432