На этом шаге мы рассмотрим объект http.client.HTTPMessage.
Рассмотрим основные методы и атрибуты объекта http.client.HTTPMessage:
>>> result.msg.as_string()
'Server: nginx/1.14.1\nDate: Thu, 03 Jan 2019 13:42:22 GMT\n
Content-Type: text/html\n
Content-Length: 185\n
Connection: keep-alive\n
Location: https://mail.ru\n
X-XSS-Protection: 1; mode=block; report=https://cspreport.mail.ru/xxssprotection\n
X-Content-Type-Options: nosniff\n\n'
>>> result.msg.items()
[('Server', 'nginx/1.14.1'),
('Date', 'Thu, 03 Jan 2019 13:42:22 GMT'), ('Content-Type', 'text/html'),
('Content-Length', '185'), ('Connection', 'keep-alive'),
('Location', 'https://mail.ru'), ('X-XSS-Protection', '1;
mode=block; report=https://cspreport.mail.ru/xxssprotection'),
('X-Content-Type-Options', 'nosniff')]
>>> result.msg.keys()
['Server', 'Date', 'Content-Type', 'Content-Length',
'Connection', 'Location', 'X-XSS-Protection', 'X-Content-Type-Options']
>>> result.msg.values()
['nginx/1.14.1', 'Thu, 03 Jan 2019 13:42:22 GMT', 'text/html',
'185', 'keep-alive', 'https://mail.ru', '1; mode=block;
report=https://cspreport.mail.ru/xxssprotection', 'nosniff']
>>> print(result.msg.get("Server")) nginx/1.14.1 >>> print(result.msg.get("X-Powered-By")) None >>> print(result.msg.get("X-Powered-By", failobj=10)) 10
>>> print(result.msg.get_all("Server")) ['nginx/1.14.1']
>>> print(result.msg.get_content_type()) text/html
>>> print(result.msg.get_content_maintype()) text
>>> print(result.msg.get_content_subtype()) html
>>> result.msg.get_content_charset ()
'windows-1251'
Для примера отправим запрос методом HEAD и выведем заголовки ответа сервера.
>>> from http.client import HTTPConnection >>> headers = { "User-Agent": "MySpider/1.0", "Accept": "text/html, text/plain, application/xml", "Accept-Language": "ru, ru-RU", "Accept-Charset": "windows-1251", "Referer": "/index.php" } >>> con = HTTPConnection("mail.ru") >>> con.request("HEAD", "/testrobots.php?%s" % data, headers=headers) >>> result = con.getresponse() # Создаем объект результата >>> print (result.msg) Server: nginx/1.14.1 Date: Thu, 03 Jan 2019 14:40:17 GMT Content-Type: text/html Content-Length: 185 Connection: keep-alive Location: https://mail.ru X-XSS-Protection: 1; mode=block; report=https://cspreport.mail.ru/xxssprotection X-Content-Type-Options: nosniff >>> result.read() # Данные не передаются, только заголовки! b'' >>> con.close()
Рассмотрим основные HTTP-заголовки и их предназначение:
Получить полное описание заголовков можно в спецификации RFC 2616, расположенной по адресу http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html. Чтобы "подсмотреть" заголовки, отправляемые Web-браузером и сервером, можно воспользоваться модулем Firebug для Firefox. Для этого на вкладке Сеть следует щелкнуть мышью на строке запроса. Кроме того, можно установить панель ieHTTPHeaders в Web-браузере Internet Explorer.
На следующем шаге мы рассмотрим обмен данными с помощью модуля urllib.request.