|
1 | | -# В данный момент разработчики обновили антибота, библиотека переписывается! |
| 1 | +<div align="center"> |
2 | 2 |
|
3 | | -# Pyaterochka API *(not official / не официальный)* |
| 3 | +# Pyaterochka API *(not official)* |
4 | 4 |
|
5 | | -Pyaterochka (Пятёрочка) - https://5ka.ru/ |
6 | | - |
7 | | -[](https://github.com/Open-Inflation/pyaterochka_api/actions?query=workflow%3A"API+Tests+Daily?query=branch%3Amain") |
| 5 | + |
| 6 | +[](https://github.com/Open-Inflation/pyaterochka_api/actions/workflows/tests.yml) |
8 | 7 |  |
9 | 8 |  |
10 | 9 | [](https://pypi.org/project/pyaterochka-api/) |
11 | | -[](https://open-inflation.github.io/pyaterochka_api/) |
| 10 | +[](https://github.com/Open-Inflation/pyaterochka_api/blob/main/LICENSE) |
12 | 11 | [](https://discord.gg/UnJnGHNbBp) |
13 | 12 | [](https://t.me/miskler_dev) |
14 | 13 |
|
15 | 14 |
|
| 15 | +Pyaterochka (Пятёрочка) - https://5ka.ru/ |
| 16 | + |
| 17 | +**[⭐ Star us on GitHub](https://github.com/Open-Inflation/pyaterochka_api)** | **[📚 Read the Docs](https://open-inflation.github.io/pyaterochka_api/quick_start)** | **[🐛 Report Bug](https://github.com/Open-Inflation/pyaterochka_api/issues)** |
| 18 | + |
| 19 | +### Принцип работы |
| 20 | + |
| 21 | +</div> |
| 22 | + |
| 23 | +> Библиотека полностью повторяет сетевую работу обычного пользователя на сайте. |
| 24 | +
|
| 25 | +<div align="center"> |
| 26 | + |
| 27 | +## Usage: |
| 28 | + |
| 29 | +</div> |
16 | 30 |
|
17 | | -## Installation / Установка: |
18 | | -1. Install package / Установка пакета: |
19 | 31 | ```bash |
20 | 32 | pip install pyaterochka_api |
21 | | -``` |
22 | | -2. ***Debian/Ubuntu Linux***: Install dependencies / Установка зависимостей: |
23 | | -```bash |
24 | | -sudo apt update && sudo apt install -y libgtk-3-0 libx11-xcb1 |
25 | | -``` |
26 | | -3. Install browser / Установка браузера: |
27 | | -```bash |
28 | | -camoufox fetch |
| 33 | +python -m camoufox fetch |
29 | 34 | ``` |
30 | 35 |
|
31 | | -### Usage / Использование: |
32 | 36 | ```py |
33 | | -from pyaterochka_api import Pyaterochka, PurchaseMode |
| 37 | +from pyaterochka_api import PyaterochkaAPI |
34 | 38 | import asyncio |
35 | | - |
| 39 | +from PIL import Image |
36 | 40 |
|
37 | 41 | async def main(): |
38 | | - async with Pyaterochka(proxy="user:password@host:port", debug=False, autoclose_browser=False, trust_env=False) as API: |
39 | | - # RUS: Вводим геоточку (самого магазина или рядом с ним) и получаем инфу о магазине |
40 | | - # ENG: Enter a geolocation (of the store or near it) and get info about the store |
41 | | - find_store = await API.find_store(longitude=37.63156, latitude=55.73768) |
42 | | - print(f"Store info output: {find_store!s:.100s}...\n") |
43 | | - |
44 | | - # RUS: Выводит список всех категорий на сайте |
45 | | - # ENG: Outputs a list of all categories on the site |
46 | | - catalog = await API.categories_list(subcategories=True, mode=API.PurchaseMode.DELIVERY) |
47 | | - print(f"Categories list output: {catalog!s:.100s}...\n") |
48 | | - |
49 | | - # RUS: Выводит список всех товаров выбранной категории (ограничение 100 элементов, если превышает - запрашивайте через дополнительные страницы) |
50 | | - # ENG: Outputs a list of all items in the selected category (limiting to 100 elements, if exceeds - request through additional pages) |
51 | | - # Страниц не сущетвует, использовать желаемый лимит (до 499) / Pages do not exist, use the desired limit (up to 499) |
52 | | - items = await API.products_list(catalog[0]['id'], limit=5) |
53 | | - print(f"Items list output: {items!s:.100s}...\n") |
54 | | - |
55 | | - # RUS: Выводит информацию о товаре (по его plu - id товара). |
56 | | - # Функция в первый раз достаточно долгая, порядка 5-9 секунды, последующие запросы около 2 секунд (если браузер не был закрыт) |
57 | | - # ENG: Outputs information about the product (by its plu - product id). |
58 | | - # The function is quite long the first time, about 5-9 seconds, subsequent requests take about 2 seconds (if the browser was not closed) |
59 | | - info = await API.product_info(43347) |
60 | | - print(f"Product output: {info["props"]["pageProps"]["props"]['productStore']!s:.100s}...\n") |
61 | | - |
62 | | - # RUS: Влияет исключительно на функцию выше (product_info), если включено, то после отработки запроса браузер закроется и кеши очищаются. |
63 | | - # Не рекомендую включать, если вам все же нужно освободить память, лучше использовать API.close(session=False, browser=True) |
64 | | - # ENG: Affects only the function above (product_info), if enabled, the browser will close after the request is processed and caches are cleared. |
65 | | - # I do not recommend enabling it, if you still need to free up memory, it is better to use API.close(session=False, browser=True) |
66 | | - API.autoclose_browser = True |
67 | | - |
68 | | - # RUS: Напрямую передается в aiohttp, так же учитывается в браузере. В первую очередь нужен для использования системного `HTTPS_PROXY`. |
69 | | - # Но системный прокси применяется, только если не указали иное напрямую в `API.proxy`. |
70 | | - # ENG: Directly passed to aiohttp, also taken into account in the browser. Primarily needed for using the system `HTTPS_PROXY`. |
71 | | - # But the system proxy is applied only if you did not specify otherwise directly in `API.proxy`. |
72 | | - API.trust_env = True |
73 | | - |
74 | | - # RUS: Выводит список последних промо-акций/новостей (можно поставить ограничитель по количеству, опционально) |
75 | | - # ENG: Outputs a list of the latest promotions/news (you can set a limit on the number, optionally) |
76 | | - news = await API.get_news(limit=5) |
77 | | - print(f"News output: {news!s:.100s}...\n") |
78 | | - |
79 | | - # RUS: Если требуется, можно настроить вывод логов в консоль |
80 | | - # ENG: If required, you can configure the output of logs in the console |
81 | | - API.debug = True |
82 | | - |
83 | | - # RUS: Скачивает картинку товара (возвращает BytesIO или None) |
84 | | - # ENG: Downloads the product image (returns BytesIO or None) |
85 | | - image = await API.download_image(url=items['products'][0]['image_links']['normal'][0]) |
86 | | - with open(image.name, 'wb') as f: |
87 | | - f.write(image.getbuffer()) |
88 | | - |
89 | | - # RUS: Можно указать свой таймаут (браузер может его интерпретировать как x2 т.к. там 2 итерации скачивания) |
90 | | - # ENG: You can specify your own timeout (the browser may interpret it as x2 since there are 2 iterations of downloading) |
91 | | - API.timeout = 7 |
92 | | - |
93 | | - # RUS: Так же как и debug, в рантайме можно переназначить прокси |
94 | | - # ENG: As with debug, you can reassign the proxy in runtime |
95 | | - API.proxy = "user:password@host:port" |
96 | | - # RUS: Изменения происходят сразу же, кроме product_info, т.к. за него отвечает браузер |
97 | | - # ENG: Changes take effect immediately, except for product_info, as it is handled by the browser |
98 | | - await API.rebuild_connection(session=False, browser=True) |
99 | | - await API.product_info(43347) |
100 | | - |
101 | | - |
102 | | -if __name__ == '__main__': |
| 42 | + async with PyaterochkaAPI() as api: |
| 43 | + |
| 44 | + # 1. Получение информации о текущем выбранном магазине доставки |
| 45 | + store_info = await api.delivery_panel_store() |
| 46 | + sap_code = store_info["selectedStore"]["sapCode"] |
| 47 | + print(f"SAP код выбранного магазина: {sap_code}\n") |
| 48 | + |
| 49 | + # 2. Получение списка всех категорий |
| 50 | + tree_resp = await api.Catalog.tree(sap_code_store_id=sap_code) |
| 51 | + categories_data = tree_resp.json() |
| 52 | + first_category = categories_data[0] |
| 53 | + print(f"Первая категория: {first_category['name']!s:.50s}...\n") |
| 54 | + |
| 55 | + # 3. Получение списка товаров в первой категории |
| 56 | + products_resp = await api.Catalog.products_list( |
| 57 | + category_id=first_category["id"], sap_code_store_id=sap_code |
| 58 | + ) |
| 59 | + products_data = products_resp.json() |
| 60 | + first_product_plu = products_data["products"][0]["plu"] |
| 61 | + print(f"Первый товар (PLU): {first_product_plu}\n") |
| 62 | + |
| 63 | + # 4. Получение подробной информации о первом товаре |
| 64 | + product_info_resp = await api.Catalog.Product.info( |
| 65 | + sap_code_store_id=sap_code, plu_id=first_product_plu |
| 66 | + ) |
| 67 | + product_info_data = product_info_resp.json() |
| 68 | + print(f"Название первого товара: {product_info_data['name']!s:.50s}...\n") |
| 69 | + |
| 70 | + # 5. Примеры использования геолокации |
| 71 | + |
| 72 | + # Поиск адресов по запросу |
| 73 | + suggest_resp = await api.Geolocation.suggest("москва") |
| 74 | + print(f"Предложения по геолокации для 'москва': {suggest_resp.json()['results'][0]['address']['formatted_address']!s:.50s}...\n") |
| 75 | + |
| 76 | + # Определение текущей геолокации |
| 77 | + geocode_resp = await api.Geolocation.geocode() |
| 78 | + pos: str = geocode_resp.json()["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"] |
| 79 | + longitude, latitude = pos.split(" ") |
| 80 | + print(f"Выбранная геолокация (долгота, широта): {longitude}, {latitude}\n") |
| 81 | + |
| 82 | + # 6. Скачивание изображения (на примере изображения первой подкатегории) |
| 83 | + image_link = first_category["categories"][0]["image_link"] |
| 84 | + image_stream = await api.General.download_image(image_link) |
| 85 | + |
| 86 | + # Пример обработки изображения с помощью PIL |
| 87 | + with Image.open(image_stream) as img: |
| 88 | + print(f"Изображение скачано. Формат: {img.format}. Размер: {img.size}\n") |
| 89 | + # img.save("first_category_image.png") # Можно сохранить локально |
| 90 | + |
| 91 | +# Запуск асинхронной функции main |
| 92 | +if __name__ == "__main__": |
103 | 93 | asyncio.run(main()) |
104 | 94 | ``` |
105 | 95 |
|
106 | | -### API Documentation / Документация API |
| 96 | +Для более подробной информации смотрите референсы [документации](https://open-inflation.github.io/pyaterochka_api/quick_start). |
107 | 97 |
|
108 | | -Автоматически сгенерированная документация API доступна по ссылке: [API Documentation](https://open-inflation.github.io/pyaterochka_api/) |
| 98 | +--- |
109 | 99 |
|
110 | | -Документация содержит подробную структуру всех ответов сервера в виде схем (на базе тестов). |
| 100 | +<div align="center"> |
111 | 101 |
|
112 | | -### Report / Обратная связь |
| 102 | +### Report |
113 | 103 |
|
114 | | -If you have any problems using it /suggestions, do not hesitate to write to the [project's GitHub](https://github.com/Open-Inflation/pyaterochka_api/issues)! |
| 104 | +If you have any problems using it / suggestions, do not hesitate to write to the [project's GitHub](https://github.com/Open-Inflation/pyaterochka_api/issues)! |
115 | 105 |
|
116 | | -Если у вас возникнут проблемы в использовании / пожелания, не стесняйтесь писать на [GitHub проекта](https://github.com/Open-Inflation/pyaterochka_api/issues)! |
| 106 | +</div> |
0 commit comments