· 5 years ago · Jun 30, 2020, 11:00 AM
1import requests
2from bs4 import BeautifulSoup
3from collections import namedtuple
4from logging import getLogger
5
6Rate = namedtuple('Rate', 'name_currency,rate_buy,rate_sell')
7logger = getLogger(__name__)
8
9
10def str_to_float(item: str):
11 item = item.replace(',', '.')
12 return float(item)
13
14
15class ParserError(Exception):
16 """Неизвестная ошибка при запросе Api BankiRu"""
17
18
19# Парсер HTML страницы BankiRu
20def parser_HTML(currency_name: str, country_name: str):
21 url = 'https://www.banki.ru/products/currency/cash'
22 headers = {
23 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
24 curr_url = url + f'/{currency_name}/{country_name}/'
25
26 try:
27 source = requests.get(curr_url, headers=headers)
28 main_text = source.text
29 soup = BeautifulSoup(main_text, 'html.parser')
30
31 convert = soup.find_all('div', {'class': 'exchange-calculator-rates table-flex__row-group'})
32
33 return convert
34 except Exception:
35 logger.exception("Parser error")
36 raise ParserError
37
38
39def get_rate(currency_name: str, country_name: str):
40 banks = dict()
41 try:
42 for info in parser_HTML(currency_name, country_name):
43 info_bank = info.find('div', {'class': 'table-flex__row item calculator-hover-icon__container'})
44 bank_name = info_bank.find('a', {'data-test': 'bank-name'})
45
46 rate_info = info_bank.find_all('div', {'data-currencies-code': currency_name.upper()})
47
48 rate_buy = str_to_float(rate_info[0].text.split('\n\n')[0].lstrip().strip().replace(' ₽', ''))
49
50 rate_sell = str_to_float(rate_info[1].text.split('\n\n')[0].lstrip().strip().replace(' ₽', ''))
51
52 banks[bank_name.text] = Rate(name_currency=currency_name.upper(), rate_buy=float(rate_buy),
53 rate_sell=float(rate_sell))
54 return banks
55
56 except Exception:
57 logger.exception("Get rate error")
58 raise AttributeError
59
60
61if __name__ == '__main__':
62 try:
63 banks_main = get_rate('usd', 'kazan~')
64 for key, value in banks_main.items():
65 print(key, value)
66 except ParserError:
67 logger.info('Parser error')
68 except AttributeError:
69 logger.info('Attribute error')