Документация Python неофициальный перевод

urllib2.md

442 строк · 31.1 КБ · обычная страница · сырой текст · скачать

1> **Источник:** https://python-all.ru/3.4/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.4/howto/urllib2.html) |10| --- | --- |1112> **Примечание**13>14> Существует французский перевод более ранней версии этого руководства, доступный по адресу [urllib2 - Le Manuel manquant](https://python-all.ru/3.4/howto/urllib2.html).1516## Введение1718Связанные статьи1920Возможно, вам также будет полезна следующая статья о получении веб-ресурсов с помощью Python:2122- [Базовая аутентификация](https://python-all.ru/3.4/howto/urllib2.html)2324  > Учебник по *базовой аутентификации* с примерами на Python.2526**urllib.request** – это модуль Python для получения 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.4/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.4/library/urllib.request.html#module-urllib.request) docs, but is supplementary to them.3132## Загрузка URL3334Простейший способ использования urllib.request выглядит так:3536```python37import urllib.request38with urllib.request.urlopen('http://python.org/') as response:39   html = response.read()40```4142If you wish to retrieve a resource via URL and store it in a temporary location, you can do so via the [`urlretrieve()`](https://python-all.ru/3.4/library/urllib.request.html#urllib.request.urlretrieve) function:4344```python45import urllib.request46local_filename, headers = urllib.request.urlretrieve('http://python.org/')47html = open(local_filename)48```4950Многие случаи использования urllib будут настолько же простыми (обратите внимание, что вместо URL с ‘http:’ мы могли бы использовать URL, начинающийся с ‘ftp:’, ‘file:’ и т.д.). Однако цель данного руководства – объяснить более сложные случаи, сосредоточившись на HTTP.5152HTTP 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:5354```python55import urllib.request5657req = urllib.request.Request('http://www.voidspace.org.uk')58with urllib.request.urlopen(req) as response:59   the_page = response.read()60```6162Обратите внимание, что urllib.request использует тот же интерфейс Request для обработки всех схем URL. Например, можно сделать FTP-запрос так:6364```python65req = urllib.request.Request('ftp://example.com/')66```6768В случае HTTP объекты Request позволяют сделать ещё две вещи: во-первых, можно передать данные для отправки на сервер. Во-вторых, можно передать серверу дополнительную информацию («метаданные») *о* данных или о самом запросе – эта информация отправляется в виде HTTP-заголовков. Рассмотрим каждую из них по очереди.6970### Данные7172Sometimes you want to send data to a URL (often the URL will refer to a CGI (Common Gateway Interface) script or other web application). With HTTP, this is often done using what’s known as a **POST** request. This is often what your browser does when you submit a HTML form that you filled in on the web. Not all POSTs have to come from forms: you can use a POST to transmit arbitrary data to your own application. In the common case of HTML forms, the data needs to be encoded in a standard way, and then passed to the Request object as the `data` argument. The encoding is done using a function from the [`urllib.parse`](https://python-all.ru/3.4/library/urllib.parse.html#module-urllib.parse) library.7374```python75import urllib.parse76import urllib.request7778url = 'http://www.someserver.com/cgi-bin/register.cgi'79values = {'name' : 'Michael Foord',80          'location' : 'Northampton',81          'language' : 'Python' }8283data = urllib.parse.urlencode(values)84data = data.encode('ascii') # data должна быть типа bytes85req = urllib.request.Request(url, data)86with urllib.request.urlopen(req) as response:87   the_page = response.read()88```8990Обратите внимание, что иногда требуются другие кодировки (например, для загрузки файлов из HTML-форм – подробнее см. [Спецификацию HTML, раздел «Отправка формы»](https://python-all.ru/3.4/howto/urllib2.html)).9192If 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.9394Это делается следующим образом:9596```python97>>> import urllib.request98>>> import urllib.parse99>>> data = {}100>>> data['name'] = 'Somebody Here'101>>> data['location'] = 'Northampton'102>>> data['language'] = 'Python'103>>> url_values = urllib.parse.urlencode(data)104>>> print(url_values)  # Порядок может отличаться от указанного ниже.  105name=Somebody+Here&language=Python&location=Northampton106>>> url = 'http://www.example.com/example.cgi'107>>> full_url = url + '?' + url_values108>>> data = urllib.request.urlopen(full_url)109```110111Обратите внимание, что полный URL создаётся добавлением `?` к URL, после которого следуют закодированные значения.112113### Заголовки114115Здесь будет рассмотрен один конкретный HTTP-заголовок, чтобы проиллюстрировать, как добавлять заголовки в HTTP-запросы.116117Some websites [\[1\]](https://python-all.ru/3.4/howto/urllib2.html#id8) dislike being browsed by programs, or send different versions to different browsers [\[2\]](https://python-all.ru/3.4/howto/urllib2.html#id9). By default urllib identifies itself as `Python-urllib/x.y` (where `x` and `y` are the major and minor version numbers of the Python release, e.g. `Python-urllib/2.5`), which may confuse the site, or just plain not work. The way a browser identifies itself is through the `User-Agent` header [\[3\]](https://python-all.ru/3.4/howto/urllib2.html#id10). When you create a Request object you can pass a dictionary of headers in. The following example makes the same request as above, but identifies itself as a version of Internet Explorer [\[4\]](https://python-all.ru/3.4/howto/urllib2.html#id11).118119```python120import urllib.parse121import urllib.request122123url = 'http://www.someserver.com/cgi-bin/register.cgi'124user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'125values = {'name' : 'Michael Foord',126          'location' : 'Northampton',127          'language' : 'Python' }128headers = { 'User-Agent' : user_agent }129130data = urllib.parse.urlencode(values)131data = data.encode('ascii')132req = urllib.request.Request(url, data, headers)133with urllib.request.urlopen(req) as response:134   the_page = response.read()135```136137Ответ также имеет два полезных метода. См. раздел [info и geturl](https://python-all.ru/3.4/howto/urllib2.html#info-and-geturl), который следует после того, как мы рассмотрим, что происходит, когда что-то идёт не так.138139## Обработка исключений140141*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.4/library/exceptions.html#ValueError), [`TypeError`](https://python-all.ru/3.4/library/exceptions.html#TypeError) etc. may also be raised).142143`HTTPError` is the subclass of `URLError` raised in the specific case of HTTP URLs.144145The exception classes are exported from the [`urllib.error`](https://python-all.ru/3.4/library/urllib.error.html#module-urllib.error) module.146147### URLError148149Часто URLError возникает из-за отсутствия сетевого соединения (нет маршрута к указанному серверу) или потому что указанный сервер не существует. В этом случае возбуждённое исключение будет иметь атрибут 'reason', который представляет собой кортеж, содержащий код ошибки и текстовое сообщение об ошибке.150151например152153```python154>>> req = urllib.request.Request('http://www.pretend_server.org')155>>> try: urllib.request.urlopen(req)156... except urllib.error.URLError as e:157...    print(e.reason)      158...159(4, 'getaddrinfo failed')160```161162### HTTPError163164Every 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).165166Все коды ошибок HTTP перечислены в разделе 10 документа RFC 2616.167168The `HTTPError` instance raised will have an integer ‘code’ attribute, which corresponds to the error sent by the server.169170#### Коды ошибок171172Поскольку обработчики по умолчанию обрабатывают перенаправления (коды в диапазоне 300), а коды в диапазоне 100-299 указывают на успех, вы обычно будете видеть коды ошибок только в диапазоне 400-599.173174[`http.server.BaseHTTPRequestHandler.responses`](https://python-all.ru/3.4/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 convenience175176```python177# Таблица, сопоставляющая коды ответов с сообщениями; записи имеют178# вид {code: (shortmessage, longmessage)}.179responses = {180    100: ('Continue', 'Request received, please continue'),181    101: ('Switching Protocols',182          'Switching to new protocol; obey Upgrade header'),183184    200: ('OK', 'Request fulfilled, document follows'),185    201: ('Created', 'Document created, URL follows'),186    202: ('Accepted',187          'Request accepted, processing continues off-line'),188    203: ('Non-Authoritative Information', 'Request fulfilled from cache'),189    204: ('No Content', 'Request fulfilled, nothing follows'),190    205: ('Reset Content', 'Clear input form for further input.'),191    206: ('Partial Content', 'Partial content follows.'),192193    300: ('Multiple Choices',194          'Object has several resources -- see URI list'),195    301: ('Moved Permanently', 'Object moved permanently -- see URI list'),196    302: ('Found', 'Object moved temporarily -- see URI list'),197    303: ('See Other', 'Object moved -- see Method and URL list'),198    304: ('Not Modified',199          'Document has not changed since given time'),200    305: ('Use Proxy',201          'You must use proxy specified in Location to access this '202          'resource.'),203    307: ('Temporary Redirect',204          'Object moved temporarily -- see URI list'),205206    400: ('Bad Request',207          'Bad request syntax or unsupported method'),208    401: ('Unauthorized',209          'No permission -- see authorization schemes'),210    402: ('Payment Required',211          'No payment -- see charging schemes'),212    403: ('Forbidden',213          'Request forbidden -- authorization will not help'),214    404: ('Not Found', 'Nothing matches the given URI'),215    405: ('Method Not Allowed',216          'Specified method is invalid for this server.'),217    406: ('Not Acceptable', 'URI not available in preferred format.'),218    407: ('Proxy Authentication Required', 'You must authenticate with '219          'this proxy before proceeding.'),220    408: ('Request Timeout', 'Request timed out; try again later.'),221    409: ('Conflict', 'Request conflict.'),222    410: ('Gone',223          'URI no longer exists and has been permanently removed.'),224    411: ('Length Required', 'Client must specify Content-Length.'),225    412: ('Precondition Failed', 'Precondition in headers is false.'),226    413: ('Request Entity Too Large', 'Entity is too large.'),227    414: ('Request-URI Too Long', 'URI is too long.'),228    415: ('Unsupported Media Type', 'Entity body in unsupported format.'),229    416: ('Requested Range Not Satisfiable',230          'Cannot satisfy request range.'),231    417: ('Expectation Failed',232          'Expect condition could not be satisfied.'),233234    500: ('Internal Server Error', 'Server got itself in trouble'),235    501: ('Not Implemented',236          'Server does not support this operation'),237    502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),238    503: ('Service Unavailable',239          'The server cannot process the request due to a high load'),240    504: ('Gateway Timeout',241          'The gateway server did not receive a timely response'),242    505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),243    }244```245246When 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:247248```python249>>> req = urllib.request.Request('http://www.python.org/fish.html')250>>> try:251...     urllib.request.urlopen(req)252... except urllib.error.HTTPError as e:253...     print(e.code)254...     print(e.read())  255...256404257b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"258  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html259  ...260  <title>Page Not Found</title>\n261  ...262```263264### Резюме265266So if you want to be prepared for `HTTPError` *or* `URLError` there are two basic approaches. I prefer the second approach.267268#### Способ 1269270```python271from urllib.request import Request, urlopen272from urllib.error import URLError, HTTPError273req = Request(someurl)274try:275    response = urlopen(req)276except HTTPError as e:277    print('The server couldn\'t fulfill the request.')278    print('Error code: ', e.code)279except URLError as e:280    print('We failed to reach a server.')281    print('Reason: ', e.reason)282else:283    # всё в порядке284```285286> **Примечание**287>288> The `except HTTPError` *must* come first, otherwise `except URLError` will *also* catch an `HTTPError`.289290#### Способ 2291292```python293from urllib.request import Request, urlopen294from urllib.error import  URLError295req = Request(someurl)296try:297    response = urlopen(req)298except URLError as e:299    if hasattr(e, 'reason'):300        print('We failed to reach a server.')301        print('Reason: ', e.reason)302    elif hasattr(e, 'code'):303        print('The server couldn\'t fulfill the request.')304        print('Error code: ', e.code)305else:306    # всё в порядке307```308309## info и geturl310311The 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.4/library/urllib.request.html#module-urllib.response)..312313**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.314315**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.316317Типичные заголовки включают ‘Content-length’, ‘Content-type’ и т.д. Смотрите [Краткий справочник HTTP-заголовков](https://python-all.ru/3.4/howto/urllib2.html) для полезного списка HTTP-заголовков с краткими пояснениями их значения и использования.318319## Открыватели и обработчики320321When you fetch a URL you use an opener (an instance of the perhaps confusingly-named [`urllib.request.OpenerDirector`](https://python-all.ru/3.4/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.322323Стоит создавать собственные opener'ы, если нужно получать URL с установленными определёнными обработчиками, например чтобы получить opener, обрабатывающий cookies, или opener, не обрабатывающий перенаправления.324325To create an opener, instantiate an `OpenerDirector`, and then call `.add_handler(some_handler_instance)` repeatedly.326327Alternatively, 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.328329Другие типы обработчиков могут обрабатывать прокси, аутентификацию и другие распространённые, но слегка специализированные ситуации.330331`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.332333Opener 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.334335## Базовая аутентификация336337To 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.4/howto/urllib2.html).338339When authentication is required, the server sends a header (as well as the 401 error code) requesting authentication. This specifies the authentication scheme and a ‘realm’. The header looks like: `WWW-Authenticate: SCHEME realm="REALM"`.340341например342343```python344WWW-Authenticate: Basic realm="cPanel Users"345```346347Затем клиент должен повторить запрос, указав соответствующие имя и пароль для области (realm) в качестве заголовка запроса. Это называется «базовая аутентификация». Чтобы упростить этот процесс, можно создать экземпляр `HTTPBasicAuthHandler` и opener для использования этого обработчика.348349`HTTPBasicAuthHandler` использует объект, называемый менеджером паролей, для управления сопоставлением URL и областей (realm) с паролями и именами пользователей. Если известно, что представляет собой область (из заголовка аутентификации, отправленного сервером), то можно использовать `HTTPPasswordMgr`. Часто область не имеет значения. В таком случае удобно использовать `HTTPPasswordMgrWithDefaultRealm`. Это позволяет указать имя пользователя и пароль по умолчанию для URL. Они будут использоваться при отсутствии альтернативной комбинации для конкретной области. Для этого нужно передать `None` в качестве аргумента realm методу `add_password`.350351URL верхнего уровня – это первый URL, требующий аутентификации. URL «глубже», чем переданный в .add\_password(), также будут соответствовать.352353```python354# создать менеджер паролей355password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()356357# Добавить имя пользователя и пароль.358# Если бы мы знали realm, мы могли бы использовать его вместо None.359top_level_url = "http://example.com/foo/"360password_mgr.add_password(None, top_level_url, username, password)361362handler = urllib.request.HTTPBasicAuthHandler(password_mgr)363364# создать "opener" (экземпляр OpenerDirector)365opener = urllib.request.build_opener(handler)366367# использовать opener для получения URL368opener.open(a_url)369370# Установить opener.371# Теперь все вызовы urllib.request.urlopen будут использовать наш opener.372urllib.request.install_opener(opener)373```374375> **Примечание**376>377> В приведённом выше примере мы передали только наш `HTTPBasicAuthHandler` в `build_opener`. По умолчанию opener'ы содержат обработчики для стандартных ситуаций – `ProxyHandler` (если задана настройка прокси, например, переменная окружения `http_proxy`), `UnknownHandler`, `HTTPHandler`, `HTTPDefaultErrorHandler`, `HTTPRedirectHandler`, `FTPHandler`, `FileHandler`, `DataHandler`, `HTTPErrorProcessor`.378379`top_level_url` на самом деле *может быть* полным URL (включая схему 'http:' и имя хоста, а также, опционально, номер порта), например, “[http://example.com/](https://python-all.ru/3.4/howto/urllib2.html)” *или* «authority» (т.е. имя хоста, опционально включая номер порта), например, “example.com” или “example.com:8080” (последний пример включает номер порта). Authority, если присутствует, не должен содержать компонент «userinfo» – например, “joe@password:example.com” неверен.380381## Прокси382383**urllib** автоматически определяет настройки прокси и использует их. Это происходит через `ProxyHandler`, который является частью стандартной цепочки обработчиков при обнаружении настройки прокси. Обычно это хорошо, но бывают случаи, когда это нежелательно [\[5\]](https://python-all.ru/3.4/howto/urllib2.html#id12). Один из способов – создать собственный `ProxyHandler`, без определённых прокси. Это делается с помощью шагов, аналогичных настройке обработчика [базовой аутентификации](https://python-all.ru/3.4/howto/urllib2.html):384385```python386>>> proxy_support = urllib.request.ProxyHandler({})387>>> opener = urllib.request.build_opener(proxy_support)388>>> urllib.request.install_opener(opener)389```390391> **Примечание**392>393> В настоящее время `urllib.request` *не поддерживает* получение `https`-ресурсов через прокси. Однако эту возможность можно включить, расширив urllib.request, как показано в рецепте [\[6\]](https://python-all.ru/3.4/howto/urllib2.html#id13).394395> **Примечание**396>397> `HTTP_PROXY` будет игнорироваться, если задана переменная `REQUEST_METHOD`; см. документацию по [`getproxies()`](https://python-all.ru/3.4/library/urllib.request.html#urllib.request.getproxies).398399## Сокеты и уровни400401Поддержка Python для получения ресурсов из сети является многоуровневой. urllib использует библиотеку [`http.client`](https://python-all.ru/3.4/library/http.client.html#module-http.client), которая, в свою очередь, использует библиотеку socket.402403Начиная с Python 2.3 можно указать, как долго сокет должен ждать ответа до истечения тайм-аута. Это может быть полезно в приложениях, которым приходится получать веб-страницы. По умолчанию модуль socket не имеет *тайм-аута* и может зависнуть. В настоящее время тайм-аут сокета не доступен на уровнях http.client или urllib.request. Однако можно установить глобальный тайм-аут по умолчанию для всех сокетов с помощью404405```python406import socket407import urllib.request408409# тайм-аут в секундах410timeout = 10411socket.setdefaulttimeout(timeout)412413# этот вызов urllib.request.urlopen теперь использует тайм-аут по умолчанию414# который мы установили в модуле socket415req = urllib.request.Request('http://www.voidspace.org.uk')416response = urllib.request.urlopen(req)417```418419---420421## Примечания422423Этот документ был проверен и доработан Джоном Ли.424425| [\[1\]](https://python-all.ru/3.4/howto/urllib2.html#id1) | Google, например. |426| --- | --- |427428| [\[2\]](https://python-all.ru/3.4/howto/urllib2.html#id2) | Определение браузера (browser sniffing) – очень плохая практика при проектировании веб-сайтов; гораздо разумнее создавать сайты с использованием веб-стандартов. К сожалению, многие сайты до сих пор отправляют разные версии разным браузерам. |429| --- | --- |430431| [\[3\]](https://python-all.ru/3.4/howto/urllib2.html#id3) | Пользовательский агент для MSIE 6 – *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'* |432| --- | --- |433434| [\[4\]](https://python-all.ru/3.4/howto/urllib2.html#id4) | Подробнее о HTTP-заголовках запросов см. [Quick Reference to HTTP Headers](https://python-all.ru/3.4/howto/urllib2.html). |435| --- | --- |436437| [\[5\]](https://python-all.ru/3.4/howto/urllib2.html#id6) | В моём случае на работе приходится использовать прокси для доступа в интернет. Если через этот прокси пытаться получить *localhost*-URL, он их блокирует. В IE настроено использование прокси, и urllib это подхватывает. Чтобы тестировать скрипты с локальным сервером, приходится запрещать urllib использовать прокси. |438| --- | --- |439440| [\[6\]](https://python-all.ru/3.4/howto/urllib2.html#id7) | Открыватель urllib для SSL-прокси (метод CONNECT): [ASPN Cookbook Recipe](https://python-all.ru/3.4/howto/urllib2.html). |441| --- | --- |442