首页 > 解决方案 > BeautifulSoup4 不能只从标签中提取文本

问题描述

我正在尝试从 xml 文件中的每个项目中提取标题、描述和 url,但是我无法提取描述标签的文本而其中没有标签。

这是我的代码:

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 文档。

如果您能在这件事上帮助我或为我指明正确的方向,我将不胜感激。

标签: pythonxmlbeautifulsoup

解决方案


由于描述是一个 html 元素,只需将其作为汤煮BeautifulSoup并从中提取文本。

desc = BeautifulSoup(item.description.text, 'html.parser')
content['description'].append(desc.text[:50]+"..")

如果你觉得很复杂,你可以使用正则表达式来摆脱它们。但我个人不会建议这样做,因为您的文本可能包含具有相同模式的普通文本。

import re
desc = re.sub("(<.*?>)", "", str(item.description.text), 0, re.IGNORECASE | re.DOTALL | re.MULTILINE)
content['description'].append(desc.text[:50]+"..")

<.*?>选择所有 HTML 标记并将其替换为空字符串。

希望这可以帮助!干杯!


推荐阅读