BeautifulSoup4不能仅从标签中提取文本

时间:2018-10-05 11:16:36

标签: python xml beautifulsoup

我正在尝试从中的每个项目中提取标题,描述和网址 一个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和一个标记,我无法摆脱它们,我尝试使用.get_text()、. string,.text,.descendants并尝试在文档,大多数时候它是相同的输出。我也不想手动删除这些标签,因为该程序应适用于任何xml文档。

如果您能在此问题上为我提供帮助或为我指明正确的方向,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

由于描述是一个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标记并将其替换为空字符串。

希望这会有所帮助!干杯!