【问题标题】:BeautifulSoup print multiple tag / attrBeautifulSoup 打印多个标签/属性
【发布时间】:2011-05-16 17:10:58
【问题描述】:

首先,这是我第一次尝试 Python,到目前为止它看起来很容易使用,尽管我仍然遇到了问题..

我正在尝试将 XML 文件更改为 rss-XML 原始 xml 源代码如下所示:

<news title="Random Title" date="Date and Time" subtitle="The article txt"></news>

它最终应该是这样的:

<item>
<pubDate>Date and Time</pubDate>
<title>Random Title</title>
<content:encoded>The article txt</content:encoded>
</item>

我正在尝试使用 python 和 BeautifulSoup 执行此操作,使用以下脚本

from BeautifulSoup import BeautifulSoup
import re

doc = [
'<news post_title="Random Title" post_date="Date and Time" post_content="The article txt">''</news></p>'
    ]
soup = BeautifulSoup(''.join(doc))

print soup.prettify()

posttitle = soup.news['post_title']
postdate = soup.news['post_date']
postcontent = soup.news['post_content']

print "<item>"
print "<pubDate>"
print postdate
print "</pubDate>"
print "<title>"
print posttitle
print "</title>"
print "<content:encoded>"
print postcontent
print "</content:encoded>"
print "</item>"

这里的问题是,它只检索最顶层的字符串 XML,而不是其他的。 任何人都可以给我一些解决这个问题的方向吗?

干杯:)

【问题讨论】:

  • 你能给我们一些示例输出吗?您对问题的描述不是很清楚,因为只有一个 XML 字符串。
  • 什么是“最上面的字符串”?
  • 代码看起来完全符合您的要求。您是否有多个要解析的 项?

标签: python xml beautifulsoup xml-parsing


【解决方案1】:

窃取代码并更正它:

for news in soup.findAll('news'):
    posttitle = news['post_title']
    postdate = news['post_date']
    postcontent = news['post_content']
    print "<item>"
    print "<pubDate>"
    print postdate
    print "</pubDate>"
    print "<title>"
    print posttitle
    print "</title>"
    print "<content:encoded>"
    print postcontent
    print "</content:encoded>"
    print "</item>"

【讨论】:

    【解决方案2】:

    您的示例 doc 变量仅包含一个 &lt;news&gt; 元素。

    但通常您需要遍历新闻元素

    类似

    for news in soup.findAll('news'):
        posttitle = news['post_title']
        postdate = news['post_date']
        postcontent = news['post_content']
        print "<item>"
        print "<pubDate>"
        print postdate
        print "</pubDate>"
        print "<title>"
        print posttitle
        print "</title>"
        print "<content:encoded>"
        print postcontent
        print "</content:encoded>"
        print "</item>"
    

    【讨论】:

    • @Sentinel,啊是的.. 我只是复制/粘贴.. 将其更改为news,因为我们正在迭代每个元素,并将当前项目存储在news。更新示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    相关资源
    最近更新 更多