ANTICHAT

ANTICHAT (https://forum.antichat.xyz/index.php)
-   Python (https://forum.antichat.xyz/forumdisplay.php?f=205)
-   -   Конвертер валюты из г#### и палок на питоне. (https://forum.antichat.xyz/showthread.php?t=1373284)

BigIce 20.12.2020 11:50

Всем привет, как-то мне нечего было делать и я решил сделать конвертер валюты, и причем зная что в питоне есть готовая библиотека для этого, но пошел трудным путем. Ну и короче решил спарсить сайт конвертер. Везде расставил комментарии, поэтому в теме расписывать каждую деталь не буду.

Python:





Код:

# Данная ***ня просто пример работы с библиотеками requests, BeautifulSoup и colorama.
import
requests
# инициализируем библиотеки.
from
bs4
import
BeautifulSoup
from
colorama
import
Back

i
=
0
# переменная i, выступает у меня в качестве костыля, так как потом нам вернет два кода.
# Создаём массив заголовков (Тут вся информация о браузере и операционной системе, сделано для того,
# чтобы сайт не заблокировал запрос.)
HEADERS
=
{
'user-agent'
:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'
,
'accept'
:
'*/*'
}
# Спрашиваем у человека тип конвертера и количество валюты.
typeofhostcheck
=
input
(
Back
.
YELLOW
+
'Введите тип конвертера валюты:\n1. usd > kzt. 2. usd > rub. 3. kzt > usd. 4. rub > usd. 5. kzt > rub. 6. rub > kzt. '
)
valueofvalute
=
input
(
Back
.
YELLOW
+
'Введите количество валюты: '
)
# Настраиваем тип конвертера.
if
typeofhostcheck
==
'1'
:
valutename
=
' kzt'
HOST
=
'https://pokur.su/usd/kzt/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'2'
:
valutename
=
' rub'
HOST
=
'https://pokur.su/usd/rub/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'3'
:
valutename
=
' usd'
HOST
=
'https://pokur.su/kzt/usd/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'4'
:
valutename
=
' usd'
HOST
=
'https://pokur.su/rub/usd/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'5'
:
valutename
=
' rub'
HOST
=
'https://pokur.su/kzt/rub/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'6'
:
valutename
=
' kzt'
HOST
=
'https://pokur.su/rub/kzt/'
+
valueofvalute
+
'/'
else
:
valutename
=
' kzt'
print
(
Back
.
RED
+
'Вы ввели неверный тип конвертера! Переключаю автоматически на: usd > kzt.'
)
HOST
=
'https://pokur.su/usd/kzt/'
+
valueofvalute
+
'/'
# Функция get_html, которая запрашивает html код страницы, и принимает в качестве параметров
# url страницы и наши заголовки.
def
get_html
(
url
,
HEADERS
)
:
r
=
requests
.
get
(
url
,
headers
=
HEADERS
)
.
text
# Запрашиваем html код страницы.
return
r
# Возращяем переменную r.
def
get_content
(
html
)
:
# создаем функцию get_content, которая в качестве параметра принимает
# уже готовый html код страницы.
global
i
# добавляем в нашу функцию переменную i.
soup
=
BeautifulSoup
(
html
,
'html.parser'
)
# создаем переменную для работы с библиотекой
# BeautifulSoup.
# Во всем коде ищем тег div с классом input-group input-group-xlg-specific input__currency.
# Нам вернет массив.
items
=
soup
.
find_all
(
'div'
,
class_
=
'input-group input-group-xlg-specific input__currency'
)
# Перебираем все элементы данного массива.
for
item
in
items
:
# Добавляем к i 1, чтобы в будующем пропустить первое значение, знаю что это можно
# Было сделать без костыля, но мне лень было искать как.
i
+=
1
if
i
==
2
:
# Если i равняется двум:
iteme
=
item
.
find
(
'input'
,
class_
=
'form-control'
)
# Ищем элемент input с классом
# form-control.
print
(
)
# Пропускаем одну строку.
# Оформлям с помощью модуля colorama и выводим результат.
print
(
Back
.
RED
+
'Результат:'
+
Back
.
RESET
+
' '
+
Back
.
GREEN
+
str
(
iteme
.
get
(
'value'
)
)
+
Back
.
RED
+
valutename
+
'.'
)
get_content
(
get_html
(
HOST
,
HEADERS
)
)
# Вызываем функцию get_content, которой передаем возращаемое значение
# функции get_html, помните, мы в функции get_html возвращали значение переменной r, так вот это оно и есть.



Изменено: Забыл сказать, модуль colorama не работает в стандартной консоли винды, он будет работать в эмуляторах консоли по типу ConEmu.

Вот код без coloram'ы:

Python:





Код:

import
requests
# инициализируем библиотеки.
from
bs4
import
BeautifulSoup
i
=
0
# переменная i, выступает у меня в качестве костыля, так как потом нам вернет два кода.
# Создаём массив заголовков (Тут вся информация о браузере и операционной системе, сделано для того,
# чтобы сайт не заблокировал запрос.)
HEADERS
=
{
'user-agent'
:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'
,
'accept'
:
'*/*'
}
# Спрашиваем у человека тип конвертера и количество валюты.
typeofhostcheck
=
input
(
'Введите тип конвертера валюты:\n1. usd > kzt. 2. usd > rub. 3. kzt > usd. 4. rub > usd. 5. kzt > rub. 6. rub > kzt. '
)
valueofvalute
=
input
(
'Введите количество валюты: '
)
# Настраиваем тип конвертера.
if
typeofhostcheck
==
'1'
:
valutename
=
' kzt'
HOST
=
'https://pokur.su/usd/kzt/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'2'
:
valutename
=
' rub'
HOST
=
'https://pokur.su/usd/rub/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'3'
:
valutename
=
' usd'
HOST
=
'https://pokur.su/kzt/usd/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'4'
:
valutename
=
' usd'
HOST
=
'https://pokur.su/rub/usd/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'5'
:
valutename
=
' rub'
HOST
=
'https://pokur.su/kzt/rub/'
+
valueofvalute
+
'/'
elif
typeofhostcheck
==
'6'
:
valutename
=
' kzt'
HOST
=
'https://pokur.su/rub/kzt/'
+
valueofvalute
+
'/'
else
:
valutename
=
' kzt'
print
(
'Вы ввели неверный тип конвертера! Переключаю автоматически на: usd > kzt.'
)
HOST
=
'https://pokur.su/usd/kzt/'
+
valueofvalute
+
'/'
# Функция get_html, которая запрашивает html код страницы, и принимает в качестве параметров
# url страницы и наши заголовки.
def
get_html
(
url
,
HEADERS
)
:
r
=
requests
.
get
(
url
,
headers
=
HEADERS
)
.
text
# Запрашиваем html код страницы.
return
r
# Возращяем переменную r.
def
get_content
(
html
)
:
# создаем функцию get_content, которая в качестве параметра принимает
# уже готовый html код страницы.
global
i
# добавляем в нашу функцию переменную i.
soup
=
BeautifulSoup
(
html
,
'html.parser'
)
# создаем переменную для работы с библиотекой
# BeautifulSoup.
# Во всем коде ищем тег div с классом input-group input-group-xlg-specific input__currency.
# Нам вернет массив.
items
=
soup
.
find_all
(
'div'
,
class_
=
'input-group input-group-xlg-specific input__currency'
)
# Перебираем все элементы данного массива.
for
item
in
items
:
# Добавляем к i 1, чтобы в будующем пропустить первое значение, знаю что это можно
# Было сделать без костыля, но мне лень было искать как.
i
+=
1
if
i
==
2
:
# Если i равняется двум:
iteme
=
item
.
find
(
'input'
,
class_
=
'form-control'
)
# Ищем элемент input с классом
# form-control.
print
(
)
# Пропускаем одну строку.
# Оформлям с помощью модуля colorama и выводим результат.
print
(
'Результат: '
+
str
(
iteme
.
get
(
'value'
)
)
+
valutename
+
'.'
)
get_content
(
get_html
(
HOST
,
HEADERS
)
)
# Вызываем функцию get_content, которой передаем возращаемое значение
# функции get_html, помните, мы в функции get_html возвращали значение переменной r, так вот это оно и есть.


Lil Xean 20.12.2020 12:35

Самый главный недостаток - нету гривны. А так сойдёт

frit 20.12.2020 12:42

Массивы! Это так сложно!

Python:





Код:

# Данная ***ня просто пример работы с библиотеками requests, BeautifulSoup и colorama.
import
requests
# инициализируем библиотеки.
from
bs4
import
BeautifulSoup
from
colorama
import
Back
in_array
=
[
'usd'
,
'usd'
,
'kzt'
,
'rub'
,
'kzt'
,
'rub'
]
into_array
=
[
'kzt'
,
'rub'
,
'usd'
,
'usd'
,
'rub'
,
'kzt'
]
i
=
0
# переменная i, выступает у меня в качестве костыля, так как потом нам вернет два кода.
# Создаём массив заголовков (Тут вся информация о браузере и операционной системе, сделано для того,
# чтобы сайт не заблокировал запрос.)
HEADERS
=
{
'user-agent'
:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'
,
'accept'
:
'*/*'
}
# Спрашиваем у человека тип конвертера и количество валюты.
typeofhostcheck
=
input
(
f'{Back.YELLOW}Введите тип конвертера валюты:\n1. usd > kzt. 2. usd > rub. 3. kzt > usd. 4. rub > usd. 5. kzt > rub. 6. rub > kzt. '
)
valueofvalute
=
input
(
f'{Back.YELLOW}Введите количество валюты: '
)
if
int
(
typeofhostcheck
)
-
1
{into_array[0]}.'
)
HOST
=
f'https://pokur.su/{in_array[0]}/{into_array[0]}/{valueofvalute}/'
typeofhostcheck
=
1
# Функция get_html, которая запрашивает html код страницы, и принимает в качестве параметров
# url страницы и наши заголовки.
def
get_html
(
url
,
HEADERS
)
:
r
=
requests
.
get
(
url
,
headers
=
HEADERS
)
.
text
# Запрашиваем html код страницы.
return
r
# Возращяем переменную r.
def
get_content
(
html
)
:
# создаем функцию get_content, которая в качестве параметра принимает
# уже готовый html код страницы.
global
i
# добавляем в нашу функцию переменную i.
soup
=
BeautifulSoup
(
html
,
'html.parser'
)
# создаем переменную для работы с библиотекой
# BeautifulSoup.
# Во всем коде ищем тег div с классом input-group input-group-xlg-specific input__currency.
# Нам вернет массив.
items
=
soup
.
find_all
(
'div'
,
class_
=
'input-group input-group-xlg-specific input__currency'
)
# Перебираем все элементы данного массива.
for
item
in
items
:
# Добавляем к i 1, чтобы в будующем пропустить первое значение, знаю что это можно
# Было сделать без костыля, но мне лень было искать как.
i
+=
1
if
i
==
2
:
# Если i равняется двум:
iteme
=
item
.
find
(
'input'
,
class_
=
'form-control'
)
# Ищем элемент input с классом
# form-control.
print
(
)
# Пропускаем одну строку.
# Оформлям с помощью модуля colorama и выводим результат.
out_value
=
iteme
.
get
(
'value'
)
print
(
f'{Back.RED}Результат:{Back.RESET}{Back.GREEN}{out_value}{Back.RED}{into_array[int(typeofhostcheck)-1]}.'
)
get_content
(
get_html
(
HOST
,
HEADERS
)
)
# Вызываем функцию get_content, которой передаем возращаемое значение
# функции get_html, помните, мы в функции get_html возвращали значение переменной r, так вот это оно и есть.


Kopamed 09.01.2021 13:53

:)

Python:





Код:

import
requests
from
bs4
import
BeautifulSoup
from
beeprint
import
pp
import
time
from
colorama
import
init
from
colorama
import
Fore
,
Style
import
pyfiglet
import
os
os
.
system
(
'cls'
if
os
.
name
==
'nt'
else
'clear'
)
#initing colorama
init
(
)
#making a class to make interaction between the front-end and back-end easier
#coding the back-end
class
Converter
:
#setting up
def
__init__
(
self
)
:
#defining the base url of the request
self
.
base_url
=
"https://pokur.su/{}/{}/{}/"
#defining where we will get the current currencies from
self
.
iso_url
=
"https://pokur.su/eur/usd/1/"
#headers - i added them early on vut they have trurned out to be useless
self
.
headers
=
{
"Accept"
:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
,
"Accept-Encoding"
:
"gzip, deflate, br"
,
"Accept-Language"
:
"en-US,en;q=0.5"
,
"Cache-Control"
:
"max-age=0"
,
"Connection"
:
"keep-alive"
,
"User-Agent"
:
"Mozilla/5.0 (X11; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0"
}
#getting all the existing currencies
def
fetch_iso
(
self
)
:
#defining the dict we will save stuff to
currencies
=
{
}
#requesting the html of the page
iso_request
=
requests
.
get
(
self
.
iso_url
)
#parsing with bs4
iso_soup
=
BeautifulSoup
(
iso_request
.
text
,
"html.parser"
)
#finding the iso name containers
iso_body
=
iso_soup
.
find
(
class_
=
"dropdown-menu dropdown-menu-right"
)
.
findChildren
(
"li"
)
#cycling through all the containers and extracting the iso (USD) and the name (American Dollar)
#we also save it to a dictionary
for
iso_container
in
iso_body
:
iso_container_children
=
iso_container
.
findChildren
(
)
#fetching the iso
iso_3
=
iso_container_children
[
1
]
.
text
#fetching the name
iso_name
=
iso_container_children
[
2
]
.
text
#adding them to the dictionary
currencies
[
iso_3
]
=
iso_name
return
currencies
#the heart of the program - converting stuff with the base_url get method
def
convert_currency
(
self
,
from_
,
to
,
amount
)
:
#we add our varibales to the base url
target_url
=
self
.
base_url
.
format
(
from_
,
to
,
amount
)
#we make a request
currency_request
=
requests
.
get
(
target_url
)
currency_soup
=
BeautifulSoup
(
currency_request
.
text
,
"html.parser"
)
#doing some bring html stuff... just finding the response
response_amount
=
currency_soup
.
find
(
class_
=
"blockquote-classic"
)
.
findChild
(
"p"
)
.
text
        response_amount
=
response_amount
.
replace
(
"  "
,
" "
)
response_amount
=
response_amount
.
replace
(
"по курсу на"
,
"on the"
)
with
open
(
"conversion_logs.txt"
,
"a"
)
as
file
:
file
.
write
(
response_amount
+
"\n"
)
#bam! just like that
return
response_amount
#returns the previous conversions the user has made
def
prev_logs
(
self
)
:
final_string
=
""
try
:
with
open
(
"conversion_logs.txt"
,
"r"
)
as
file
:
logs
=
file
.
readlines
(
)
for
line
in
range
(
len
(
logs
)
)
:
#adding the conversion to the string that will be shown at the end
final_string
=
Fore
.
CYAN
+
str
(
line
+
1
)
+
Style
.
RESET_ALL
+
". "
+
logs
[
line
]
+
"\n"
+
final_string
#checking if we even have any logs
except
FileNotFoundError
:
final_string
=
"You have no logs :(\nTry making some conversions!"
return
final_string
#making the frontend
class
app
:
def
__init__
(
self
)
:
#starting the app
self
.
cnvrt
=
Converter
(
)
self
.
__version__
=
"0.0.2"
#the heart of our app
def
main_menu
(
self
)
:
#making a fancy banner
ascii_banner
=
pyfiglet
.
figlet_format
(
"Currency Converter "
+
self
.
__version__
)
#waiting for the user to enter a valid input
while
True
:
print
(
Fore
.
CYAN
,
ascii_banner
)
print
(
Fore
.
YELLOW
+
"Main Menu"
)
print
(
Fore
.
RED
+
"-"
*
10
)
print
(
Fore
.
CYAN
+
"1"
+
Style
.
RESET_ALL
+
". Make a conversion"
)
print
(
Fore
.
CYAN
+
"2"
+
Style
.
RESET_ALL
+
". View previous conversions"
)
print
(
)
#fancy input
option
=
input
(
Fore
.
GREEN
+
"["
+
Fore
.
YELLOW
+
"Main Menu"
+
Fore
.
GREEN
+
"]"
+
Fore
.
CYAN
+
":$ "
+
Style
.
RESET_ALL
)
self
.
clear
(
)
if
"1"
in
option
:
self
.
make_conversion
(
)
elif
"2"
in
option
:
self
.
see_logs
(
)
def
see_logs
(
self
)
:
ascii_banner
=
pyfiglet
.
figlet_format
(
"Currency Converter "
+
self
.
__version__
)
#just opening up a file and printing it out... see Convert.prev_logs()
print
(
Fore
.
CYAN
,
ascii_banner
)
print
(
Fore
.
YELLOW
+
"Previous Logs"
)
print
(
Fore
.
RED
+
"-"
*
10
)
print
(
Style
.
RESET_ALL
+
self
.
cnvrt
.
prev_logs
(
)
)
print
(
)
option
=
input
(
Fore
.
GREEN
+
"{"
+
Fore
.
RED
+
"Press Enter To Continue"
+
Fore
.
GREEN
+
"}"
+
Style
.
RESET_ALL
+
Fore
.
GREEN
+
"["
+
Fore
.
YELLOW
+
"Previous Logs"
+
Fore
.
GREEN
+
"]"
+
Fore
.
CYAN
+
":$ "
+
Style
.
RESET_ALL
)
self
.
clear
(
)
def
make_conversion
(
self
)
:
#getting the existing isos. see Convert.fetch_iso()
#banner
ascii_banner
=
pyfiglet
.
figlet_format
(
"Currency Converter "
+
self
.
__version__
)
isos
=
self
.
cnvrt
.
fetch_iso
(
)
while
True
:
print
(
Fore
.
CYAN
,
ascii_banner
)
print
(
Fore
.
YELLOW
+
"Currency Converter"
)
print
(
Fore
.
RED
+
"-"
*
10
)
print
(
Fore
.
YELLOW
+
"Please choose a currency you would like to convert"
+
Fore
.
GREEN
+
" from"
+
Style
.
RESET_ALL
)
print
(
Fore
.
RED
+
"THIS IS CASE SENSITIVE!"
)
print
(
)
isos
=
self
.
cnvrt
.
fetch_iso
(
)
for
i
in
isos
:
#printing out the isos
print
(
Fore
.
CYAN
+
i
+
Style
.
RESET_ALL
+
" - "
+
isos
[
i
]
)
print
(
)
option
=
input
(
Fore
.
GREEN
+
"["
+
Fore
.
YELLOW
+
"Currency Converter"
+
Fore
.
GREEN
+
"]"
+
Fore
.
CYAN
+
":$ "
+
Style
.
RESET_ALL
)
self
.
clear
(
)
if
option
in
isos
:
#validating input
from_conversion
=
option
.
lower
(
)
break
while
True
:
print
(
Fore
.
CYAN
,
ascii_banner
)
print
(
Fore
.
YELLOW
+
"Currency Converter"
)
print
(
Fore
.
RED
+
"-"
*
10
)
print
(
Fore
.
YELLOW
+
"Please choose a currency you would like to convert"
+
Fore
.
GREEN
+
" to"
+
Style
.
RESET_ALL
)
print
(
Fore
.
RED
+
"THIS IS CASE SENSITIVE!"
)
print
(
)
isos
=
self
.
cnvrt
.
fetch_iso
(
)
for
i
in
isos
:
print
(
Fore
.
CYAN
+
i
+
Style
.
RESET_ALL
+
" - "
+
isos
[
i
]
)
print
(
)
option
=
input
(
Fore
.
GREEN
+
"["
+
Fore
.
YELLOW
+
"Currency Converter"
+
Fore
.
GREEN
+
"]"
+
Fore
.
CYAN
+
":$ "
+
Style
.
RESET_ALL
)
self
.
clear
(
)
if
option
in
isos
:
to_conversion
=
option
.
lower
(
)
break
while
True
:
try
:
print
(
Fore
.
CYAN
,
ascii_banner
)
print
(
Fore
.
YELLOW
+
"Currency Converter"
)
print
(
Fore
.
RED
+
"-"
*
10
)
print
(
Fore
.
YELLOW
+
"Please choose how much money you would like to convert"
+
Style
.
RESET_ALL
)
print
(
Fore
.
RED
+
"THIS MUST BE A NUMBER SUCH AS 23 BUT NOT A DECIMAL SUCH AS 89.50"
)
print
(
)
print
(
Fore
.
GREEN
+
"From: "
+
Style
.
RESET_ALL
+
from_conversion
)
print
(
Fore
.
GREEN
+
"to: "
+
Style
.
RESET_ALL
+
to_conversion
)
print
(
Fore
.
GREEN
+
"Amount: "
+
Style
.
RESET_ALL
+
"?"
)
print
(
)
option
=
input
(
Fore
.
GREEN
+
"["
+
Fore
.
YELLOW
+
"Currency Converter"
+
Fore
.
GREEN
+
"]"
+
Fore
.
CYAN
+
":$ "
+
Style
.
RESET_ALL
)
self
.
clear
(
)
amount_conversion
=
int
(
option
)
break
#if the input is not a number, ValueError will be raised and the screen will be cleared
except
ValueError
:
self
.
clear
(
)
print
(
Fore
.
CYAN
,
ascii_banner
)
print
(
Fore
.
YELLOW
+
"Currency Converter"
)
print
(
Fore
.
RED
+
"-"
*
10
)
print
(
)
print
(
Fore
.
GREEN
+
self
.
cnvrt
.
convert_currency
(
from_conversion
,
to_conversion
,
amount_conversion
)
)
print
(
)
option
=
input
(
Fore
.
GREEN
+
"{"
+
Fore
.
RED
+
"Press Enter To Continue"
+
Fore
.
GREEN
+
"}"
+
Style
.
RESET_ALL
+
Fore
.
GREEN
+
"["
+
Fore
.
YELLOW
+
"Currency Converter"
+
Fore
.
GREEN
+
"]"
+
Fore
.
CYAN
+
":$ "
+
Style
.
RESET_ALL
)
self
.
clear
(
)
def
clear
(
self
)
:
os
.
system
(
'cls'
if
os
.
name
==
'nt'
else
'clear'
)
if
__name__
==
"__main__"
:
app
=
app
(
)
app
.
main_menu
(
)



Время: 20:46