Содержание страницы
HOWTO получение интернет-ресурсов с помощью пакета urllib¶HOWTO 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.
Загрузка URL¶Fetching URLs
Простейший способ использования urllib.request выглядит так:
import urllib.request
response = urllib.request.urlopen('http://python.org/')
html = response.read()
Многие случаи использования 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)
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.open(full_url)
Обратите внимание, что полный URL создаётся добавлением ? к URL, после которого следуют закодированные значения.
Заголовки¶Headers
Здесь будет рассмотрен один конкретный HTTP-заголовок, чтобы проиллюстрировать, как добавлять заголовки в HTTP-запросы.
Некоторым сайтам [2] не нравится, когда их просматривают программы, или они отправляют разные версии разным браузерам [3]. По умолчанию urllib идентифицирует себя как Python-urllib/x.y (где x и y – это номера старшей и младшей версии релиза Python, например Python-urllib/2.5), что может сбивать сайт с толку или просто не работать. Способ, которым браузер идентифицирует себя, – это заголовок User-Agent [4]. При создании объекта Request можно передать словарь заголовков. В следующем примере выполняется тот же запрос, что и выше, но идентифицируется как версия 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)
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
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<?xml-stylesheet href="./css/ht2html.css"
type="text/css"?>
<html><head><title>Error 404: File Not Found</title>
...... etc...
Резюме¶Wrapping it Up
So if you want to be prepared for HTTPError or URLError there are two basic approaches. I prefer the second approach.
Способ 1¶Number 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.
Способ 2¶Number 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 и geturl¶info 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.
Когда требуется аутентификация, сервер отправляет заголовок (а также код ошибки 401), запрашивающий аутентификацию. В нём указывается схема аутентификации и «realm» (область). Заголовок выглядит так: 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, 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 без определения прокси. Это делается с помощью шагов, аналогичных настройке обработчика Basic Authentication:
>>> proxy_support = urllib.request.ProxyHandler({})
>>> opener = urllib.request.build_opener(proxy_support)
>>> urllib.request.install_opener(opener)
Примечание
В настоящее время urllib.request не поддерживает получение https-ресурсов через прокси. Однако эту возможность можно включить, расширив urllib.request, как показано в рецепте [7].
Сокеты и уровни¶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. |