Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lesson1 #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
.idea
.venv
.venv
products
test
64 changes: 64 additions & 0 deletions parser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import requests
import json

from pathlib import Path
from time import sleep


class Parser:
def __init__(self, url: str, path: Path):
self.url = url
self.path = path

def _get_response(self, url, params):
while True:
response = requests.get(url=url, params=params)
if response.status_code == 200:
return response
sleep(1)

def run(self):
response = requests.get(self.url)
for r in response.json():
id = r["parent_group_code"]
name = r["parent_group_name"]
self._parse(id, name)


def _parse(self, id, name):
url = "https://5ka.ru/api/v2/special_offers/"
params = {"records_per_page": 12,
"page": 1,
"categories": id
}
response = self._get_response(url=url, params=params)
product_list = []

while url:
data = response.json()
url = data["next"]
try:
response = requests.get(url)
except:
continue
for product in data["results"]:
product_list.append(product)

data = [{"name": name, "code": id, "products": product_list}]
save_path = self.path.joinpath(f"{id}.json")
self._save(data, save_path)

@staticmethod
def _save(data, save_path):
jdata = json.dumps(data, ensure_ascii=False)
save_path.write_text(jdata, encoding="UTF-8")


if __name__ == "__main__":
url = "https://5ka.ru/api/v2/categories/"
path = Path(__file__).parent.joinpath("products")
if not path.exists():
path.mkdir()

parser = Parser(url, path)
parser.run()