Вы можете выполнить итерацию по самым внешним div
из id='dictionary-neodict-es'
с помощью рекурсивной функции, чтобы учесть тот факт, что существует несколько вложенных div
с классом indent--FyTYr
:
from bs4 import BeautifulSoup as soup
import requests, bs4
def has_class(d, c):
return any(c in i.attrs.get('class', []) or has_class(getattr(i, 'contents', []), c) for i in d if i != '\n' and not isinstance(i, bs4.NavigableString))
def get_sentences(d):
if 'indent--FyTYr' in d.attrs.get('class', []) and not has_class(d.contents, 'indent--FyTYr'):
yield [d.div.span.text, d.div.em.text]
else:
for i in filter(lambda x:x != '\n' and not isinstance(x, bs4.NavigableString), getattr(d, 'contents', [])):
yield from get_sentences(i)
result = list(get_sentences(soup(requests.get('https://www.spanishdict.com/translate/rojo').text, 'html.parser').find('div', {'id':'dictionary-neodict-es'})))
Теперь у вас есть доступ ко всем предложениям:
[['The sky turned red at sundown.', 'El cielo se tornó rojo al atardecer.'], ['No quiero ver esa propaganda roja.', "I don't want to see that red propaganda."], ['Ella cree que me veo mejor vestida de rojo, pero no estoy segura.', "She thinks I look best dressed in red, but I'm not sure."], ['Durante la Guerra Fría, a los izquierdistas se les llamaba rojos.', 'During the Cold War, the leftists were called reds.']]
Для доступа к нужной вам строке:
print(result[0][0])
Вывод:
'The sky turned red at sundown.'