Skip to content

Commit bee3f77

Browse files
committed
Added "cbr_ru/xml_metall/main_v2.py"
1 parent 2129e9f commit bee3f77

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

cbr_ru/xml_metall/main_v2.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
__author__ = 'ipetrash'
5+
6+
7+
import datetime as DT
8+
import decimal
9+
import enum
10+
from dataclasses import dataclass
11+
12+
import requests
13+
from bs4 import BeautifulSoup, Tag
14+
15+
16+
class MetalEnum(enum.IntEnum):
17+
Gold = 1
18+
Silver = 2
19+
Platinum = 3
20+
Palladium = 4
21+
22+
23+
@dataclass
24+
class MetalRate:
25+
date: DT.date
26+
code: MetalEnum
27+
amount: decimal.Decimal
28+
29+
@classmethod
30+
def parse_from_xml(cls, tag: Tag) -> 'MetalRate':
31+
date = DT.datetime.strptime(tag['date'], '%d.%m.%Y').date()
32+
code = int(tag['code'])
33+
amount = decimal.Decimal(tag.sell.text.replace(',', '.'))
34+
35+
return cls(date, MetalEnum(code), amount)
36+
37+
38+
decimal.getcontext().prec = 2
39+
40+
41+
def get_next_date(date: DT.date) -> DT.date:
42+
return (date + DT.timedelta(days=31)).replace(day=1)
43+
44+
45+
def get_date_str(date: DT.date) -> str:
46+
return date.strftime('%d/%m/%Y')
47+
48+
49+
# TODO: ...
50+
START_DATE_REQ1 = DT.date(year=2000, month=1, day=1)
51+
52+
# TODO: db.py
53+
54+
# TODO: нужен код, который возьмет последнюю загруженную дату и составит список пар date_req1 и date_req2 по месяцам
55+
# т.е. из api всегда берем только за 1 месяц
56+
57+
date_req1 = DT.date.today().replace(day=1)
58+
date_req2 = get_next_date(date_req1)
59+
60+
params = {
61+
'date_req1': get_date_str(date_req1),
62+
'date_req2': get_date_str(date_req2),
63+
}
64+
rs = requests.get('http://www.cbr.ru/scripts/xml_metall.asp', params=params)
65+
print(rs)
66+
rs.raise_for_status()
67+
68+
root = BeautifulSoup(rs.content, 'html.parser')
69+
metal_rates = [
70+
MetalRate.parse_from_xml(r)
71+
for r in root.select('Record')
72+
]
73+
print(*metal_rates, sep='\n')

0 commit comments

Comments
 (0)