Как указать определённую валюту, которая будет показана на сайте для дальнейшего парсинга
Проблема заключается в том, что мне необходимо выводить цену предмета ИСКЛЮЧИТЕЛЬНО в рублях, но код выдаёт значение всегда в разных валютах (рубли, йены, тенге, гривны, доллары, злоты и т.д.). Это идёт от особенностей самой торговой площадке стима. Как именно можно конкретизировать вывод валюты в рублях
Сам код:
from bs4 import BeautifulSoup
import requests
url = 'https://steamcommunity.com/market/listings/730/MAC-10%20%7C%20Ensnared%20%28Well-Worn%29'
page = requests.get(url)
soup = BeautifulSoup(page.text, "html.parser")
name = soup.find("div", class_="market_listing_item_name_block").find("span")
cena = soup.find("span", class_="market_table_value").find("span")
print(name.text, cena.text)
Ответы (1 шт):
Автор решения: Edward Grachev
→ Ссылка
Я тут чутка накидал. Курс валюты запрашиваем только 1 раз, так как цб может ставить ограничения на кол-во запросов в сутки
import requests
from bs4 import BeautifulSoup
import json
from decimal import Decimal
class SteamParser(object):
def __init__(self):
self.base_url = 'https://steamcommunity.com/market/{0}'
self.exchange_rates = ExchangeRates()
if self.exchange_rates.json_exchange_rates is None:
raise TypeError(self.exchange_rates)
def is_float(self, number: str) -> bool:
try:
float(number)
return True
except TypeError:
return False
def parsing_page(self, page: str) -> str:
soup = BeautifulSoup(page, "html.parser")
name = soup.find("div", class_="market_listing_item_name_block").find("span").text
cena = soup.find("span", class_="market_table_value").find("span").text
for i, k in self.exchange_rates.currency_icons.items():
if k in cena:
cena = cena.replace(k, "").replace(",", ".").strip()
if self.is_float(cena):
cena = float(cena)
prc = "%.2f" % self.exchange_rates.calculate_the_cost(i, cena)
return (f"Наименование: {name}\nЦена в {k}:{cena}\nЦена в рублях: {prc}")
def get_product_page(self, product: str) -> str:
"""
:param product: Ссылка на товар в виде "listings/730/Dreams%20%26%20Nightmares%20Case"
:return:
"""
url = self.base_url.format(product)
response = requests.get(url)
if response.status_code == 200:
return self.parsing_page(response.text)
class ExchangeRates(object):
def __init__(self):
self.__url = 'https://www.cbr-xml-daily.ru/daily_json.js'
self.json_exchange_rates = self.__get_the_exchange_rate()
self.currency_icons = {
"KRW": '₩',
"EUR": '€',
"JPY": '¥'
}
def __get_the_exchange_rate(self) -> json or None:
response = requests.get(self.__url)
if response.status_code == 200:
return response.json()
def calculate_the_cost(self, currency_code: str, sum: float) -> Decimal:
denomination = self.json_exchange_rates["Valute"][currency_code]["Value"]
nominal = self.json_exchange_rates["Valute"][currency_code]["Nominal"]
return (float(denomination) / int(nominal)) * sum
parser = SteamParser()
print(parser.get_product_page("listings/730/MAC-10%20%7C%20Ensnared%20%28Well-Worn%29"))