Как передать переменную в параметр BeautifulSoup

Если написать параметр напрямую:

from bs4 import BeautifulSoup
import requests

def get_currency_today():
    resp = requests.get("http://www.cbr.ru/scripts/XML_daily.asp")
    soap = BeautifulSoup(resp.content, "xml")
    currency = soap.find("CharCode", text="TRY")
    print(currency)
get_currency_today()

То выдает результат:

<CharCode>TRY</CharCode>

Если хочу передать переменную в качестве параметра к text таким образом:

from bs4 import BeautifulSoup
import requests

def get_currency_today():
    county_currency = "'TRY'"
    resp = requests.get("http://www.cbr.ru/scripts/XML_daily.asp")
    soap = BeautifulSoup(resp.content, "xml")
    currency = soap.find("CharCode", text=county_currency)
    print(currency)
get_currency_today()

То в результате выдает:

None

Как можно передать county_currency, что бы результат был TRY?


Ответы (1 шт):

Автор решения: gil9red

Предлагаю вариант через цикл и поиск значения по названию валюты.

Из-за структуры данных, думаю, это самое простое решение:

<ValCurs Date="19.01.2021" name="Foreign Currency Market">
    <Valute ID="R01010">
        <NumCode>036</NumCode>
        <CharCode>AUD</CharCode>
        <Nominal>1</Nominal>
        <Name>Австралийский доллар</Name>
        <Value>56,7525</Value>
    </Valute>
    ...

Пример:

from bs4 import BeautifulSoup
import requests

def get_currency_today(char_code="USD"):
    rs = requests.get("http://www.cbr.ru/scripts/XML_daily.asp")
    root = BeautifulSoup(rs.content, "xml")
    for valute in root.find_all("Valute"):
        if valute.find('CharCode', text=char_code):
            return valute.find('Value').text

print(get_currency_today())
# 73,9735

print(get_currency_today('TRY'))
# 98,3076
→ Ссылка