Я пытаюсь извлечь заголовок, описание и URL из каждого элемента в XML-файле, но у меня возникают проблемы с извлечением текста тега описания без тегов внутри него.
Вот мой код:
import urllib.request
from bs4 import BeautifulSoup
def read_xml(url):
"""reads xml string from url"""
with urllib.request.urlopen(url) as source:
html=source.read()
return BeautifulSoup(html,'xml')
def read_content(html_file):
"""reads title,description and url from xml file"""
content={'title':[],'description':[],'url':[]}
item_lines=html_file.find_all('item')
#item_lines is a list of the content within <item></item> tags
for item in item_lines:
content['title'].append(item.title.string)
content['description'].append(item.description.text[:50]+"..")
content['url'].append(item.link.text)
return content
soup=read_xml('https://www.gamespot.com/feeds/game-news/')
content=read_content(soup)
for content in display_content.values():
print(content)
print("\n")
И это вывод (показывает только первые элементы списков):
['Fortnite Guide: Week 2 Secret Battle Banner Location (Season 6 Hunting Party Challenge)', 'Getting Away With Crime In Red Dead Redemption 2 Is Tricky', "This Is How Red Dead Redemption 2's Cores, Health, And Stats Work", "Red Dead Redemption 2: Here's How The Horses ...]
['<p>Season 6 of <a href="https://www.gamespot.com/f..', '<p><a href="https://www.gamespot.com/red-dead-rede..', '<p>In terms of scale, scope, gameplay systems, and..', '<p>One of the key areas of <a href="https://www.ga..', '<p>Week 2 of <a href="https://www.gamespot.com/for..', '<p>Forza Horizon is back for another year, and tha..', '<p>From all that we\'ve seen of ...]
['https://www.gamespot.com/articles/fortnite-guide-week-2-secret-battle-banner-locatio/1100-6462272/', 'https://www.gamespot.com/articles/getting-away-with-crime-in-red-dead-redemption-2-i/1100-6462203/', 'https://www.gamespot.com/articles/this-is-how-red-dead-redemption-2s-cores-health-an/1100-6462201/', ...]
Как видите, во втором списке есть теги p и a,от которого я не могу избавиться, я пытался .get_text (), .string, .text, .descendants и пытался найти решение в документации, в большинстве случаев это один и тот же вывод.Я также не хочу удалять эти теги вручную, потому что программа должна быть применима для любого XML-документа.
Я был бы очень признателен, если бы вы могли помочь мне в этом вопросе или указать мне верное направление.