Оглавление
Как послать Multipart-Encoded файл
Requests позволяет легко послать на сервер Multipart-Encoded файлы:
>>> url = 'http://httpbin.org/post' >>> files = {'file': open('report.xls', 'rb')} >>> r = requests.post(url, files=files) >>> r.text { ... "files": { "file": "<censored...binary...data>" }, ... }
Вы можете установить имя файла, content-type и заголовки в явном виде:
>>> url = 'http://httpbin.org/post' >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})} >>> r = requests.post(url, files=files) >>> r.text { ... "files": { "file": "<censored...binary...data>" }, ... }
При желании, вы можете отправить строки, которые будут приняты в виде файлов:
>>> url = 'http://httpbin.org/post' >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')} >>> r = requests.post(url, files=files) >>> r.text { ... "files": { "file": "some,data,to,send\nanother,row,to,send\n" }, ... }
В случае, если вы отправляете очень большой файл как , вы можете захотеть отправить запрос потоком. По умолчанию не поддерживает этого, но есть отдельный пакет, который это делает — .
Для отправки нескольких файлов в одном запросе, обратитесь к дополнительной документации.
.authenticators
The class or decorator will ensure that this property is automatically set to a list of instances, based on the set on the view or based on the setting.
You won’t typically need to access this property.
Note: You may see a raised when calling the or properties. These errors originate from an authenticator as a standard , however it’s necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the originates from the authenticator and will instead assume that the request object does not have a or property. The authenticator will need to be fixed.
REST framework supports a few browser enhancements such as browser-based , and forms.
The Message Body
According to the HTTP specification, , , and the less common requests pass their data through the message body rather than through parameters in the query string. Using , you’ll pass the payload to the corresponding function’s parameter.
takes a dictionary, a list of tuples, bytes, or a file-like object. You’ll want to adapt the data you send in the body of your request to the specific needs of the service you’re interacting with.
For example, if your request’s content type is , you can send the form data as a dictionary:
>>>
You can also send that same data as a list of tuples:
>>>
If, however, you need to send JSON data, you can use the parameter. When you pass JSON data via , will serialize your data and add the correct header for you.
httpbin.org is a great resource created by the author of , Kenneth Reitz. It’s a service that accepts test requests and responds with data about the requests. For instance, you can use it to inspect a basic request:
>>>
Работа с данными JSON в Python
JSON (JavaScript Object Notation) — это язык API. JSON — это способ кодирования структур данных, который простоту чтения данных машинами. JSON — это основной формат, в котором данные передаются туда и обратно в API, и большинство серверов API отправляют свои ответы в формате JSON.
JSON выглядит так, как будто он содержит словари, списки, строки и целые числа Python. Вы можете думать о JSON как о комбинации этих объектов, представленных в виде строк.
Рассмотрим пример:
Python имеет отличный инструментарий для работы с данными в формате JSON (пакет json — является частью стандартной библиотеки). Мы можем конвертировать списки и словари в JSON, а также конвертировать строки в списки и словари.
Библиотека JSON имеет две основные функции:
- — принимает объект Python и преобразует его в строку.
- — принимает строку JSON и преобразует (загружает) ее в объект Python.
Функция особенно полезна, поскольку мы можем использовать ее для печати отформатированной строки, которая облегчает понимание вывода JSON.
Рассмотрим пример:
# Импорт библиотеки requests import requests # Запрос GET (Отправка только URL без параметров) response = requests.get("http://api.open-notify.org/astros.json") # Вывод кода print(response.status_code) # Вывод ответа, полученного от сервера API print(response.json())
Результат:
200 {'people': , 'message': 'success', 'number': 3}
Теперь попробуем применить функцию dump() — структура данных станет более наглядна:
# Импорт библиотеки requests import requests # Импорт библиотеки json import json def jprint(obj): # create a formatted string of the Python JSON object text = json.dumps(obj, sort_keys=True, indent=4) print(text) # Запрос GET (Отправка только URL без параметров) response = requests.get("http://api.open-notify.org/astros.json") # Вывод ответа, через пользовательскую функцию jprint jprint(response.json())
Результат:
{ "message": "success", "number": 3, "people": }
Main Classes¶
These classes are the main interface to :
- class (*, session: Union = None, url: str = ‘https://example.org/’, html: Union, default_encoding: str = ‘utf-8’) → None
-
An HTML document, ready for parsing.
Parameters: - url – The URL from which the HTML originated, used for .
- html – HTML from which to base the parsing upon (optional).
- default_encoding – Which encoding to default to.
-
All found links on page, in absolute form
(learn more).
-
The base URL for the page. Supports the tag
(learn more).
-
The encoding string to be used, extracted from the HTML and
headers.
- (selector: str = ‘*’, *, containing: Union] = None, clean: bool = False, first: bool = False, _encoding: str = None) → Union, _ForwardRef(‘Element’)]
-
Given a CSS Selector, returns a list of
objects or a single one.Parameters: - selector – CSS Selector to use.
- clean – Whether or not to sanitize the found HTML of and tags.
- containing – If specified, only return elements that contain the provided text.
- first – Whether or not to return just the first result.
- _encoding – The encoding format.
Example CSS Selectors:
See W3School’s CSS Selectors Reference
for more details.If is , only returns the first
found.
-
The full text content (including links) of the
or .
-
Unicode representation of the HTML content
(learn more).
-
All found links on page, in as–is form.
-
lxml representation of the
or .
-
PyQuery representation
of the or .
-
Bytes representation of the HTML content.
(learn more).
- (retries: int = 8, script: str = None, wait: float = 0.2, scrolldown=False, sleep: int = 0, reload: bool = True, timeout: Union = 8.0, keep_page: bool = False)
-
Reloads the response in Chromium, and replaces HTML content
with an updated version, with JavaScript executed.Parameters: - retries – The number of times to retry loading the page in Chromium.
- script – JavaScript to execute upon page load (optional).
- wait – The number of seconds to wait before loading the page, preventing timeouts (optional).
- scrolldown – Integer, if provided, of how many times to page down.
- sleep – Integer, if provided, of how many long to sleep after initial render.
- reload – If , content will not be loaded from the browser, but will be provided from memory.
- keep_page – If will allow you to interact with the browser page through .
If is specified, the page will scrolldown the specified
number of times, after sleeping the specified amount of time
(e.g. ).If just is provided, the rendering will wait n seconds, before
returning.If is specified, it will execute the provided JavaScript at
runtime. Example:script = """ () => { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight, deviceScaleFactor: window.devicePixelRatio, } } """
Returns the return value of the executed , if any is provided:
>>> r.html.render(script=script) {'width': 800, 'height': 600, 'deviceScaleFactor': 1}
Warning: If you use keep_page, you’re responsable for closing each page, since
opening to many at scale may crach the browser.Warning: the first time you run this method, it will download
Chromium into your home directory ().
- (template: str) → parse.Result
-
Search the for the given Parse template.
Parameters: template – The Parse template to use.
- (template: str) → Union, _ForwardRef(‘Result’)]
-
Search the (multiple times) for the given parse
template.Parameters: template – The Parse template to use.
-
The text content of the
or .
- (selector: str, *, clean: bool = False, first: bool = False, _encoding: str = None) → Union, typing.List, str, _ForwardRef(‘Element’)]
-
Given an XPath selector, returns a list of
objects or a single one.Parameters: - selector – XPath Selector to use.
- clean – Whether or not to sanitize the found HTML of and tags.
- first – Whether or not to return just the first result.
- _encoding – The encoding format.
If a sub-selector is specified (e.g. ), a simple
list of results is returned.See W3School’s XPath Examples
for more details.If is , only returns the first
found.
6: Использование Translate API
Теперь давайте попробуем использовать Yandex Translate API для выполнения запроса на перевод текста на другой язык.
Чтобы использовать API, сначала необходимо зарегистрироваться. После регистрации перейдите в Translate API и создайте ключ API. Получив ключ, добавьте его в свой файл script.py как константу.
Вот ссылка, по которой можно все сделать.
Ключ API нужен нам потому, что с его помощью Яндекс сможет аутентифицировать нас каждый раз, когда мы хотим использовать его API. Ключ API представляет собой упрощенную форму аутентификации, он добавляется в конец URL-адреса запроса при отправке.
Узнать, какой URL нужно отправить, чтобы использовать API, можно в документации Яндекса.
Там можно найти всю информацию, необходимую для использования Translate API для перевода текста.
Если в URL вы видите амперсанды (&), вопросительные знаки (?) и знаки равенства (=), вы можете быть уверены, что такой URL предназначен для запросов GET. Эти символы задают соответствующие параметры URL-адреса.
Обычно в квадратных скобках ([]) указываются опциональные фрагменты. В этом случае таковыми являются format, options и callback, в то время как key, text, and lang обязательно должны присутствовать в запросе.
Давайте добавим код для отправки запроса на этот URL. Вы можете заменить первый созданный нами запрос в файле script.py следующим кодом:
Есть два способа добавить параметры. Их можно добавить в конец URL-адреса напрямую, а можно сделать так, чтобы запросы делали это за нас. Чтобы сделать последнее, мы можем создать словарь для наших параметров. Обязательными элементами будут ключ, текст и язык. Давайте создадим словарь, используя ключ API, текст ‘Hello’ и языки ‘en-es’ (то есть текст нужно перевести с английского на испанский).
Другие языковые коды вы можете найти здесь в столбце 639-1.
Давайте создадим словарь параметров, используя функцию dict(), и передадим ей ключи и значения, которые должны быть в этом словаре. Добавьте в файл script.py:
Теперь мы возьмем словарь параметров и передадим его в функцию .get().
После этого запросы начнут добавляться к URL-адресу самостоятельно.
Теперь давайте добавим оператор print для текста ответа и посмотрим, что вернется в результате.
Здесь мы видим три вещи. Сначала идет код состояния, который в точности совпадает с кодом состояния самого ответа; затем идет язык, который мы выбрали; в конце мы видим переведенный текст.
Попробуйте еще раз, указав в качестве языка en-fr, и вы должны увидеть «Bonjour» в ответе.
Давайте посмотрим на заголовки для этого конкретного ответа.
Очевидно, заголовки будут отличаться, потому что мы обращаемся к другому серверу. В этом случае тип контента – application/json, а не text/html. Это означает, что данные могут быть интерпретированы как JSON.
Когда application/json является типом контента, мы можем сделать так, чтобы запросы преобразовывали ответ в словарь и список, чтобы легче получать доступ к данным.
Чтобы данные были обработаны как JSON, мы используем метод .json() для объекта ответа.
Если вы отобразите его, вы увидите, что данные выглядят так же, но формат немного отличается.
Теперь это не простой текст, который вы получаете из res.text, а версия словаря.
Допустим, мы хотим получить доступ к тексту. Поскольку теперь это словарь, мы можем использовать ключ text.
И теперь мы увидим только данные для этого ключа. В этом случае мы получим список из одного элемента. Если вам нужно получить этот текст в списке, можно получить к нему доступ по индексу.
И теперь на экране будет только переведенное слово.
Меняя параметры, вы будете получать разные результаты. Давайте изменим текст, вместо Hello будет Goodbye, а также изменим целевой язык на испанский и отправим запрос снова.
Также можно попробовать перевести более длинный текст на другие языки и посмотреть, какие ответы дает API.
Retrieving definitions from a dictionary
In the following example, we find definitions of a term
on the www.dictionary.com.
To parse HTML, we use the module.
$ pip install lxml
We install the module with
the tool.
get_term.py
#!/usr/bin/env python3 import requests as req from lxml import html import textwrap term = "dog" resp = req.get("http://www.dictionary.com/browse/" + term) root = html.fromstring(resp.content) for sel in root.xpath("//span"): if sel.text: s = sel.text.strip() if (len(s) > 3): print(textwrap.fill(s, width=50))
In this script, we find the definitions of the term dog on .
The module is used to parse the HTML code.
Note: The tags that contain the definitions may change overnight.
In such case we would need to adapt the script.
from lxml import html
The module can be used to parse HTML.
import textwrap
The module is used to wrap text to a certain width.
resp = req.get("http://www.dictionary.com/browse/" + term)
To perform a search, we append the term at the end of the URL.
root = html.fromstring(resp.content)
We need to use rather than
because implicitly expects bytes as input.
(The returns content in bytes whereas
as Unicode text.
for sel in root.xpath("//span"): if sel.text: s = sel.text.strip() if (len(s) > 3): print(textwrap.fill(s, width=50))
We parse the content. The main definitions are located inside the tag, which
has the attribute.
We improve the formatting by removing excessive white space and stray
characters. The text width has maximum of 50 characters. Note that such parsing
is subject to change.
$ ./get_term.py a domesticated canid, any carnivore of the dog family Canidae, having prominent canine teeth and, in the wild state, a long and slender muzzle, a deep-chested muscular body, a bushy tail, and large, erect ears. ...
This is a partial list of the definitions.
HTML Sessions¶
These sessions are for making HTTP requests:
- class (mock_browser=True, *args, **kwargs)
-
A consumable session, for cookie persistence and connection pooling,
amongst other things.- ()
-
Closes all adapters and as such the session
- (url, **kwargs)
-
Sends a DELETE request. Returns object.
Parameters: - url – URL for the new object.
- **kwargs – Optional arguments that takes.
Return type: requests.Response
- (url, **kwargs)
-
Sends a GET request. Returns object.
Parameters: - url – URL for the new object.
- **kwargs – Optional arguments that takes.
Return type: requests.Response
- (url)
-
Returns the appropriate connection adapter for the given URL.
Return type: requests.adapters.BaseAdapter
- (resp)
-
Receives a Response. Returns a redirect URI or
- (url, **kwargs)
-
Sends a HEAD request. Returns object.
Parameters: - url – URL for the new object.
- **kwargs – Optional arguments that takes.
Return type: requests.Response
- (url, proxies, stream, verify, cert)
-
Check the environment and merge it with some settings.
Return type:
- (prefix, adapter)
-
Registers a connection adapter to a prefix.
Adapters are sorted in descending order by prefix length.
- (url, **kwargs)
-
Sends a OPTIONS request. Returns object.
Parameters: - url – URL for the new object.
- **kwargs – Optional arguments that takes.
Return type: requests.Response
- (url, data=None, **kwargs)
-
Sends a PATCH request. Returns object.
Parameters: - url – URL for the new object.
- data – (optional) Dictionary, bytes, or file-like object to send in the body of the .
- **kwargs – Optional arguments that takes.
Return type: requests.Response
- (url, data=None, json=None, **kwargs)
-
Sends a POST request. Returns object.
Parameters: - url – URL for the new object.
- data – (optional) Dictionary, bytes, or file-like object to send in the body of the .
- json – (optional) json to send in the body of the .
- **kwargs – Optional arguments that takes.
Return type: requests.Response
- (request)
-
Constructs a for
transmission and returns it. The has settings
merged from the instance and those of the
.Parameters: request – instance to prepare with this
session’s settings.Return type: requests.PreparedRequest
- (url, data=None, **kwargs)
-
Sends a PUT request. Returns object.
Parameters: - url – URL for the new object.
- data – (optional) Dictionary, bytes, or file-like object to send in the body of the .
- **kwargs – Optional arguments that takes.
Return type: requests.Response
- (prepared_request, response)
-
When being redirected we may want to strip authentication from the
request to avoid leaking credentials. This method intelligently removes
and reapplies authentication where possible to avoid credential loss.
- (prepared_request, response)
-
When being redirected we may want to change the method of the request
based on certain specs or browser behavior.
- (prepared_request, proxies)
-
This method re-evaluates the proxy configuration by considering the
environment variables. If we are redirected to a URL covered by
NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
proxy keys for this URL (in case they were stripped by a previous
redirect).This method also replaces the Proxy-Authorization header where
necessary.Return type:
- (resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)
-
Receives a Response. Returns a generator of Responses or Requests.
- (request, **kwargs)
-
Send a given PreparedRequest.
Return type: requests.Response
Request Objects¶
The following methods describe ’s public interface,
and so all may be overridden in subclasses. It also defines several
public attributes that can be used by clients to inspect the parsed
request.
-
The original URL passed to the constructor.
Changed in version 3.4.
Request.full_url is a property with setter, getter and a deleter. Getting
returns the original request URL with the
fragment, if it was present.
-
The URI scheme.
-
The URI authority, typically a host, but may also contain a port
separated by a colon.
-
The original host for the request, without port.
-
The URI path. If the uses a proxy, then selector
will be the full URL that is passed to the proxy.
-
The entity body for the request, or if not specified.
Changed in version 3.4: Changing value of now deletes “Content-Length”
header if it was previously set or calculated.
-
boolean, indicates whether the request is unverifiable as defined
by RFC 2965.
-
The HTTP request method to use. By default its value is ,
which means that will do its normal computation
of the method to be used. Its value can be set (thus overriding the default
computation in ) either by providing a default
value by setting it at the class level in a subclass, or by
passing a value in to the constructor via the method
argument.New in version 3.3.
Changed in version 3.4: A default value can now be set in subclasses; previously it could only
be set via the constructor argument.
- ()
-
Return a string indicating the HTTP request method. If
is not , return its value, otherwise return
if is , or if it’s not.
This is only meaningful for HTTP requests.Changed in version 3.3: get_method now looks at the value of .
- (key, val)
-
Add another header to the request. Headers are currently ignored by all
handlers except HTTP handlers, where they are added to the list of headers sent
to the server. Note that there cannot be more than one header with the same
name, and later calls will overwrite previous calls in case the key collides.
Currently, this is no loss of HTTP functionality, since all headers which have
meaning when used more than once have a (header-specific) way of gaining the
same functionality using only one header.
- (key, header)
-
Add a header that will not be added to a redirected request.
- (header)
-
Return whether the instance has the named header (checks both regular and
unredirected).
- (header)
-
Remove named header from the request instance (both from regular and
unredirected headers).New in version 3.4.
- ()
-
Return the URL given in the constructor.
Changed in version 3.4.
Returns
- (host, type)
-
Prepare the request by connecting to a proxy server. The host and type will
replace those of the instance, and the instance’s selector will be the original
URL given in the constructor.
- (header_name, default=None)
-
Return the value of the given header. If the header is not present, return
the default value.
- ()
-
Return a list of tuples (header_name, header_value) of the Request headers.
Наш первый запрос
Для начала мы используем библиотеку Requests для отправки запроса на сайт Scotch.io. Создайте файл с именем и добавьте в него следующий код. В этой статье мы рассматриваем небольшое количество кода, поэтому если что-то изменится, вы можете просто обновить существующий код вместо добавления новых строк.
script.py
Этот код просто отправляет запрос GET на сайт Scotch.io. Это такой же тип запроса, какой используется вашим браузером для просмотра этой страницы, и единственное отличие заключается в том, что библиотека Requests не может выполнить рендеринг кода HTML, и поэтому вы получите просто код HTML и другую информацию, содержащуюся в ответе.
Здесь мы используем функцию , однако Requests также позволяет использовать при отправке запросов и другие функции, в том числе и .
Для отправки запроса нужно запустить файл script.py.
Вот что вы получите в результате: запуск .
Чтение ответа
Ответ на HTTP-запрос может содержать множество заголовков, содержащих различную информацию.
httpbin – популярный веб-сайт для тестирования различных операций HTTP. В этой статье мы будем использовать httpbin или get для анализа ответа на запрос GET. Прежде всего, нам нужно узнать заголовок ответа и то, как он выглядит. Вы можете использовать любой современный веб-браузер, чтобы найти его, но для этого примера мы будем использовать браузер Google Chrome:
- В Chrome откройте URL-адрес http://httpbin.org/get, щелкните правой кнопкой мыши в любом месте страницы и выберите параметр «Проверить».
- Это откроет новое окно в вашем браузере. Обновите страницу и перейдите на вкладку «Сеть».
- Эта вкладка «Сеть» покажет вам все различные типы сетевых запросов, сделанных браузером. Щелкните запрос «получить» в столбце «Имя» и выберите вкладку «Заголовки» справа.
Содержание «Заголовков ответа» является нашим обязательным элементом. Вы можете увидеть пары ключ-значение, содержащие различную информацию о ресурсе и запросе. Попробуем разобрать эти значения с помощью библиотеки запросов:
import requests r = requests.get('http://httpbin.org/get') print(r.headers) print(r.headers) print(r.headers) print(r.headers) print(r.headers) print(r.headers) print(r.headers) print(r.headers)
Мы получили информацию заголовка с помощью r.headers, и мы можем получить доступ к каждому значению заголовка с помощью определенных ключей
Обратите внимание, что ключ не чувствителен к регистру.. Точно так же попробуем получить доступ к значению ответа
Заголовок выше показывает, что ответ находится в формате JSON: (Content-type: application/json). Библиотека запросов поставляется с одним встроенным парсером JSON, и мы можем использовать request.get (‘url’). Json() для анализа его как объекта JSON. Затем значение для каждого ключа результатов ответа можно легко проанализировать, как показано ниже:
Точно так же попробуем получить доступ к значению ответа. Заголовок выше показывает, что ответ находится в формате JSON: (Content-type: application/json). Библиотека запросов поставляется с одним встроенным парсером JSON, и мы можем использовать request.get (‘url’). Json() для анализа его как объекта JSON. Затем значение для каждого ключа результатов ответа можно легко проанализировать, как показано ниже:
import requests r = requests.get('http://httpbin.org/get') response = r.json() print(r.json()) print(response) print(response) print(response) print(response) print(response) print(response) print(response) print(response) print(response)
Приведенный выше код напечатает следующий вывод:
{'headers': {'Host': 'httpbin.org', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Accept': '*/*', 'User-Agent': 'python-requests/2.9.1'}, 'url': 'http://httpbin.org/get', 'args': {}, 'origin': '103.9.74.222'} {} {'Host': 'httpbin.org', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Accept': '*/*', 'User-Agent': 'python-requests/2.9.1'} */* gzip, deflate close httpbin.org python-requests/2.9.1 103.9.74.222 http://httpbin.org/get
Третья строка, ierjson(), напечатала значение ответа JSON. Мы сохранили значение JSON в ответе переменной, а затем распечатали значение для каждого ключа
Обратите внимание, что в отличие от предыдущего примера, пара «ключ-значение» чувствительна к регистру.
Подобно JSON и текстовому контенту, мы можем использовать запросы для чтения контента ответа в байтах для нетекстовых запросов, используя свойство .content. Это автоматически декодирует gzip и дефлирует закодированные файлы.
Использование Translate API
Теперь перейдем к чему-то более интересному. Мы используем API Яндекс.Перевод (Yandex Translate API) для выполнения запроса на перевод текста на другой язык.
Чтобы использовать API, нужно предварительно войти в систему. После входа в систему перейдите к Translate API и создайте ключ API. Когда у вас будет ключ API, добавьте его в свой файл в качестве константы. Далее приведена ссылка, с помощью которой вы можете сделать все перечисленное: https://tech.yandex.com/translate/
script.py
Ключ API нужен, чтобы Яндекс мог проводить аутентификацию каждый раз, когда мы хотим использовать его API. Ключ API представляет собой облегченную форму аутентификации, поскольку он добавляется в конце URL запроса при отправке.
Чтобы узнать, какой URL нам нужно отправить для использования API, посмотрим документацию Яндекса.
Там мы найдем всю информацию, необходимую для использования их Translate API для перевода текста.
Если вы видите URL с символами амперсанда (&), знаками вопроса (?) или знаками равенства (=), вы можете быть уверены, что это URL запроса GET. Эти символы задают сопутствующие параметры для URL.
Обычно все, что размещено в квадратных скобках ([]), будет необязательным. В данном случае для запроса необязательны формат, опции и обратная связь, но обязательны параметры key, text и lang.
Добавим код для отправки на этот URL. Замените первый созданный нами запрос на следующий:
script.py
Существует два способа добавления параметров. Мы можем прямо добавить параметры в конец URL, или библиотека Requests может сделать это за нас. Для последнего нам потребуется создать словарь параметров. Нам нужно указать три элемента: ключ, текст и язык. Создадим словарь, используя ключ API, текст и язык , т. к. нам требуется перевод с английского на испанский.
Другие коды языков можно посмотреть здесь. Нам нужен столбец 639-1.
Мы создаем словарь параметров, используя функцию , и передаем ключи и значения, которые хотим использовать в нашем словаре.
script.py
Теперь возьмем словарь параметров и передадим его функции .
script.py
Когда мы передаем параметры таким образом, Requests автоматически добавляет параметры в URL за нас.
Теперь добавим команду печати текста ответа и посмотрим, что мы получим в результате.
script.py
Мы видим три вещи. Мы видим код состояния, который совпадает с кодом состояния ответа, мы видим заданный нами язык и мы видим переведенный текст внутри списка. Итак, мы должны увидеть переведенный текст .
Повторите эту процедуру с кодом языка en-fr, и вы получите ответ .
script.py
Посмотрим заголовки полученного ответа.
script.py
Разумеется, заголовки должны быть другими, поскольку мы взаимодействуем с другим сервером, но в данном случае мы видим тип контента application/json вместо text/html. Это означает, что эти данные могут быть интерпретированы в формате JSON.
Если ответ имеет тип контента application/json, библиотека Requests может конвертировать его в словарь и список, чтобы нам было удобнее просматривать данные.
Для обработки данных в формате JSON мы используем метод на объекте response.
Если вы распечатаете его, вы увидите те же данные, но в немного другом формате.
script.py
Причина отличия заключается в том, что это уже не обычный текст, который мы получаем из файла res.text. В данном случае это печатная версия словаря.
Допустим, нам нужно получить доступ к тексту. Поскольку сейчас это словарь, мы можем использовать ключ текста.
script.py
Теперь мы видим данные только для этого одного ключа. В данном случае мы видим список из одного элемента, так что если мы захотим напрямую получить текст в списке, мы можем использовать указатель для доступа к нему.
script.py
Теперь мы видим только переведенное слово.
Разумеется, если мы изменим параметры, мы получим другие результаты. Изменим переводимый текст с на , изменим язык перевода на испанский и снова отправим запрос.
script.py
Попробуйте перевести более длинный текст на другие языки и посмотрите, какие ответы будет вам присылать API.

Эта тема закрыта для публикации ответов.