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

HOWTO получение интернет-ресурсов с помощью пакета urllibHOWTO Fetch Internet Resources Using The urllib Package

Автор:Michael Foord

Примечание

Существует французский перевод более ранней версии этого руководства, доступный по адресу urllib2 - Le Manuel manquant.

ВведениеIntroduction

urllib.request – это модуль Python для получения URL (Uniform Resource Locators). Он предоставляет очень простой интерфейс в виде функции urlopen. Эта функция может получать URL с использованием различных протоколов. Также он предоставляет немного более сложный интерфейс для обработки типичных ситуаций, таких как базовая аутентификация, куки, прокси и т.д. Эти возможности обеспечиваются объектами, называемыми обработчиками и открывателями.

urllib.request поддерживает получение URL для многих «схем URL» (определяемых строкой до двоеточия в URL – например, «ftp» – это схема URL для «ftp://python.org/») с использованием связанных с ними сетевых протоколов (например, FTP, HTTP). Данное руководство фокусируется на наиболее распространённом случае – HTTP.

For straightforward situations urlopen is very easy to use. But as soon as you encounter errors or non-trivial cases when opening HTTP URLs, you will need some understanding of the HyperText Transfer Protocol. The most comprehensive and authoritative reference to HTTP is RFC 2616. This is a technical document and 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 docs, but is supplementary to them.

Загрузка URLFetching URLs

Простейший способ использования urllib.request выглядит так:

import urllib.request
response = urllib.request.urlopen('http://python.org/')
html = response.read()

If you wish to retrieve a resource via URL and store it in a temporary location, you can do so via the urlretrieve() function:

import urllib.request
local_filename, headers = urllib.request.urlretrieve('http://python.org/')
html = open(local_filename)

Многие случаи использования urllib будут настолько же простыми (обратите внимание, что вместо URL с ‘http:’ мы могли бы использовать URL, начинающийся с ‘ftp:’, ‘file:’ и т.д.). Однако цель данного руководства – объяснить более сложные случаи, сосредоточившись на HTTP.

HTTP 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:

import urllib.request

req = urllib.request.Request('http://www.voidspace.org.uk')
response = urllib.request.urlopen(req)
the_page = response.read()

Обратите внимание, что urllib.request использует тот же интерфейс Request для обработки всех схем URL. Например, можно сделать FTP-запрос так:

req = urllib.request.Request('ftp://example.com/')

В случае HTTP объекты Request позволяют сделать ещё две вещи: во-первых, можно передать данные для отправки на сервер. Во-вторых, можно передать серверу дополнительную информацию («метаданные») о данных или о самом запросе – эта информация отправляется в виде HTTP-заголовков. Рассмотрим каждую из них по очереди.

ДанныеData

Иногда требуется отправить данные на URL (часто URL ссылается на CGI-скрипт (Common Gateway Interface) [1] или другое веб-приложение). В HTTP это обычно делается с помощью так называемого POST-запроса. Именно так ваш браузер отправляет заполненную HTML-форму. Не все POST-запросы должны приходить из форм: можно использовать POST для передачи произвольных данных в собственное приложение. В типичном случае HTML-форм данные необходимо закодировать стандартным способом, а затем передать в объект Request в качестве аргумента data. Кодирование выполняется с помощью функции из библиотеки urllib.parse.

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }

data = urllib.parse.urlencode(values)
data = data.encode('utf-8') # data должна быть типа bytes
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
the_page = response.read()

Обратите внимание, что иногда требуются другие кодировки (например, для загрузки файлов из HTML-форм – подробнее см. Спецификацию HTML, раздел «Отправка формы»).

If 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.

Это делается следующим образом:

>>> import urllib.request
>>> import urllib.parse
>>> data = {}
>>> data['name'] = 'Somebody Here'
>>> data['location'] = 'Northampton'
>>> data['language'] = 'Python'
>>> url_values = urllib.parse.urlencode(data)
>>> print(url_values)  # Порядок может отличаться от указанного ниже.  
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values
>>> data = urllib.request.urlopen(full_url)

Обратите внимание, что полный URL создаётся добавлением ? к URL, после которого следуют закодированные значения.

ЗаголовкиHeaders

Здесь будет рассмотрен один конкретный HTTP-заголовок, чтобы проиллюстрировать, как добавлять заголовки в HTTP-запросы.

Some websites [2] dislike being browsed by programs, or send different versions to different browsers [3]. 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 [4]. 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 [5].

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

data  = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()

Ответ также имеет два полезных метода. См. раздел info и geturl, который следует после того, как мы рассмотрим, что происходит, когда что-то идёт не так.

Обработка исключенийHandling Exceptions

urlopen raises URLError when it cannot handle a response (though as usual with Python APIs, built-in exceptions such as ValueError, TypeError etc. may also be raised).

HTTPError is the subclass of URLError raised in the specific case of HTTP URLs.

The exception classes are exported from the urllib.error module.

URLError

Часто URLError возникает из-за отсутствия сетевого соединения (нет маршрута к указанному серверу) или потому что указанный сервер не существует. В этом случае возбуждённое исключение будет иметь атрибут 'reason', который представляет собой кортеж, содержащий код ошибки и текстовое сообщение об ошибке.

например

>>> req = urllib.request.Request('http://www.pretend_server.org')
>>> try: urllib.request.urlopen(req)
... except urllib.error.URLError as e:
...    print(e.reason)      
...
(4, 'getaddrinfo failed')

HTTPError

Every HTTP response from the server contains a numeric “status code”. Sometimes the status code indicates that the server is unable to fulfil the request. The default handlers will handle some of these responses for you (for example, if the response is a “redirection” that requests the client fetch the document from 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).

Все коды ошибок HTTP перечислены в разделе 10 документа RFC 2616.

The HTTPError instance raised will have an integer ‘code’ attribute, which corresponds to the error sent by the server.

Коды ошибокError Codes

Поскольку обработчики по умолчанию обрабатывают перенаправления (коды в диапазоне 300), а коды в диапазоне 100-299 указывают на успех, вы обычно будете видеть коды ошибок только в диапазоне 400-599.

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 convenience

# Таблица, сопоставляющая коды ответов с сообщениями; записи имеют
# вид {code: (shortmessage, longmessage)}.
responses = {
    100: ('Continue', 'Request received, please continue'),
    101: ('Switching Protocols',
          'Switching to new protocol; obey Upgrade header'),

    200: ('OK', 'Request fulfilled, document follows'),
    201: ('Created', 'Document created, URL follows'),
    202: ('Accepted',
          'Request accepted, processing continues off-line'),
    203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
    204: ('No Content', 'Request fulfilled, nothing follows'),
    205: ('Reset Content', 'Clear input form for further input.'),
    206: ('Partial Content', 'Partial content follows.'),

    300: ('Multiple Choices',
          'Object has several resources -- see URI list'),
    301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
    302: ('Found', 'Object moved temporarily -- see URI list'),
    303: ('See Other', 'Object moved -- see Method and URL list'),
    304: ('Not Modified',
          'Document has not changed since given time'),
    305: ('Use Proxy',
          'You must use proxy specified in Location to access this '
          'resource.'),
    307: ('Temporary Redirect',
          'Object moved temporarily -- see URI list'),

    400: ('Bad Request',
          'Bad request syntax or unsupported method'),
    401: ('Unauthorized',
          'No permission -- see authorization schemes'),
    402: ('Payment Required',
          'No payment -- see charging schemes'),
    403: ('Forbidden',
          'Request forbidden -- authorization will not help'),
    404: ('Not Found', 'Nothing matches the given URI'),
    405: ('Method Not Allowed',
          'Specified method is invalid for this server.'),
    406: ('Not Acceptable', 'URI not available in preferred format.'),
    407: ('Proxy Authentication Required', 'You must authenticate with '
          'this proxy before proceeding.'),
    408: ('Request Timeout', 'Request timed out; try again later.'),
    409: ('Conflict', 'Request conflict.'),
    410: ('Gone',
          'URI no longer exists and has been permanently removed.'),
    411: ('Length Required', 'Client must specify Content-Length.'),
    412: ('Precondition Failed', 'Precondition in headers is false.'),
    413: ('Request Entity Too Large', 'Entity is too large.'),
    414: ('Request-URI Too Long', 'URI is too long.'),
    415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
    416: ('Requested Range Not Satisfiable',
          'Cannot satisfy request range.'),
    417: ('Expectation Failed',
          'Expect condition could not be satisfied.'),

    500: ('Internal Server Error', 'Server got itself in trouble'),
    501: ('Not Implemented',
          'Server does not support this operation'),
    502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
    503: ('Service Unavailable',
          'The server cannot process the request due to a high load'),
    504: ('Gateway Timeout',
          'The gateway server did not receive a timely response'),
    505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
    }

When an error is raised the server responds by returning an HTTP error code 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:

>>> req = urllib.request.Request('http://www.python.org/fish.html')
>>> try:
...     urllib.request.urlopen(req)
... except urllib.error.HTTPError as e:
...     print(e.code)
...     print(e.read())  
...
404
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
  ...
  <title>Page Not Found</title>\n
  ...

РезюмеWrapping it Up

So if you want to be prepared for HTTPError or URLError there are two basic approaches. I prefer the second approach.

Способ 1Number 1

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request(someurl)
try:
    response = urlopen(req)
except HTTPError as e:
    print('The server couldn\'t fulfill the request.')
    print('Error code: ', e.code)
except URLError as e:
    print('We failed to reach a server.')
    print('Reason: ', e.reason)
else:
    # всё в порядке

Примечание

The except HTTPError must come first, otherwise except URLError will also catch an HTTPError.

Способ 2Number 2

from urllib.request import Request, urlopen
from urllib.error import  URLError
req = Request(someurl)
try:
    response = urlopen(req)
except URLError as e:
    if hasattr(e, 'reason'):
        print('We failed to reach a server.')
        print('Reason: ', e.reason)
    elif hasattr(e, 'code'):
        print('The server couldn\'t fulfill the request.')
        print('Error code: ', e.code)
else:
    # всё в порядке

info и geturlinfo and geturl

The response returned by urlopen (or the HTTPError instance) has two useful methods info() and geturl() and is defined in the module urllib.response..

geturl - this returns the real URL of the page fetched. This is useful because urlopen (or the opener object used) may have followed a redirect. The URL of the page fetched may not be the same as the URL requested.

info - this returns a dictionary-like object that describes the page fetched, particularly the headers sent by the server. It is currently an http.client.HTTPMessage instance.

Типичные заголовки включают ‘Content-length’, ‘Content-type’ и т.д. Смотрите Краткий справочник HTTP-заголовков для полезного списка HTTP-заголовков с краткими пояснениями их значения и использования.

Открыватели и обработчикиOpeners and Handlers

When you fetch a URL you use an opener (an instance of the perhaps confusingly-named 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.

Стоит создавать собственные opener'ы, если нужно получать URL с установленными определёнными обработчиками, например чтобы получить opener, обрабатывающий cookies, или opener, не обрабатывающий перенаправления.

To create an opener, instantiate an OpenerDirector, and then call .add_handler(some_handler_instance) repeatedly.

Alternatively, you can use build_opener, which is a convenience function for creating opener objects with a single function call. build_opener adds several handlers by default, but provides a quick way to add more and/or override the default handlers.

Другие типы обработчиков могут обрабатывать прокси, аутентификацию и другие распространённые, но слегка специализированные ситуации.

install_opener can be used to make an opener object the (global) default opener. This means that calls to urlopen will use the opener you have installed.

Opener objects have an open method, which can be called directly to fetch urls in the same way as the urlopen function: there’s no need to call install_opener, except as a convenience.

Базовая аутентификацияBasic Authentication

To illustrate creating and installing a handler we will use the HTTPBasicAuthHandler. For a more detailed discussion of this subject – including an explanation of how Basic Authentication works - see the Basic Authentication Tutorial.

When 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".

например

WWW-Authenticate: Basic realm="cPanel Users"

Затем клиент должен повторить запрос, указав соответствующие имя и пароль для области (realm) в качестве заголовка запроса. Это называется «базовая аутентификация». Чтобы упростить этот процесс, можно создать экземпляр HTTPBasicAuthHandler и opener для использования этого обработчика.

HTTPBasicAuthHandler использует объект, называемый менеджером паролей, для управления сопоставлением URL и областей (realm) с паролями и именами пользователей. Если известно, что представляет собой область (из заголовка аутентификации, отправленного сервером), то можно использовать HTTPPasswordMgr. Часто область не имеет значения. В таком случае удобно использовать HTTPPasswordMgrWithDefaultRealm. Это позволяет указать имя пользователя и пароль по умолчанию для URL. Они будут использоваться при отсутствии альтернативной комбинации для конкретной области. Для этого нужно передать None в качестве аргумента realm методу add_password.

URL верхнего уровня – это первый URL, требующий аутентификации. URL «глубже», чем переданный в .add_password(), также будут соответствовать.

# создать менеджер паролей
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Добавить имя пользователя и пароль.
# Если бы мы знали realm, мы могли бы использовать его вместо None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# создать "opener" (экземпляр OpenerDirector)
opener = urllib.request.build_opener(handler)

# использовать opener для получения URL
opener.open(a_url)

# Установить opener.
# Теперь все вызовы urllib.request.urlopen будут использовать наш opener.
urllib.request.install_opener(opener)

Примечание

В примере выше мы передали только HTTPBasicAuthHandler в build_opener. По умолчанию открыватели имеют обработчики для обычных ситуаций – ProxyHandler (если задана настройка прокси, например, переменная окружения http_proxy), UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor.

top_level_url на самом деле может быть полным URL (включая схему 'http:' и имя хоста, а также, опционально, номер порта), например, “http://example.com/или «authority» (т.е. имя хоста, опционально включая номер порта), например, “example.com” или “example.com:8080” (последний пример включает номер порта). Authority, если присутствует, не должен содержать компонент «userinfo» – например, “joe@password:example.com” неверен.

ПроксиProxies

urllib автоматически определяет настройки прокси и использует их. Это происходит через ProxyHandler, который является частью стандартной цепочки обработчиков при обнаружении настройки прокси. Обычно это хорошо, но бывают случаи, когда это нежелательно [6]. Один из способов – создать собственный ProxyHandler, без определённых прокси. Это делается с помощью шагов, аналогичных настройке обработчика базовой аутентификации:

>>> proxy_support = urllib.request.ProxyHandler({})
>>> opener = urllib.request.build_opener(proxy_support)
>>> urllib.request.install_opener(opener)

Примечание

В настоящее время urllib.request не поддерживает получение https-ресурсов через прокси. Однако эту возможность можно включить, расширив urllib.request, как показано в рецепте [7].

Примечание

HTTP_PROXY` будет игнорироваться, если задана переменная REQUEST_METHOD; см. документацию по getproxies().

Сокеты и уровниSockets and Layers

Поддержка Python для получения ресурсов из сети является многоуровневой. urllib использует библиотеку http.client, которая, в свою очередь, использует библиотеку socket.

Начиная с Python 2.3 можно указать, как долго сокет должен ждать ответа до истечения тайм-аута. Это может быть полезно в приложениях, которым приходится получать веб-страницы. По умолчанию модуль socket не имеет тайм-аута и может зависнуть. В настоящее время тайм-аут сокета не доступен на уровнях http.client или urllib.request. Однако можно установить глобальный тайм-аут по умолчанию для всех сокетов с помощью

import socket
import urllib.request

# тайм-аут в секундах
timeout = 10
socket.setdefaulttimeout(timeout)

# этот вызов urllib.request.urlopen теперь использует тайм-аут по умолчанию
# который мы установили в модуле socket
req = urllib.request.Request('http://www.voidspace.org.uk')
response = urllib.request.urlopen(req)

ПримечанияFootnotes

Этот документ был проверен и доработан Джоном Ли.

[1]Введение в протокол CGI см. в Writing Web Applications in Python.
[2]Например, Google. Правильный способ использовать Google из программы – это, конечно, использовать PyGoogle. См. Voidspace Google для примеров использования Google API.
[3]Определение браузера (browser sniffing) – очень плохая практика при проектировании веб-сайтов; гораздо разумнее создавать сайты с использованием веб-стандартов. К сожалению, многие сайты до сих пор отправляют разные версии разным браузерам.
[4]Пользовательский агент для MSIE 6 – 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'
[5]Подробнее о HTTP-заголовках запросов см. Quick Reference to HTTP Headers.
[6]В моём случае на работе приходится использовать прокси для доступа в интернет. Если через этот прокси пытаться получить localhost-URL, он их блокирует. В IE настроено использование прокси, и urllib это подхватывает. Чтобы тестировать скрипты с локальным сервером, приходится запрещать urllib использовать прокси.
[7]Открыватель urllib для SSL-прокси (метод CONNECT): ASPN Cookbook Recipe.