解析带有来自RSS feed的子项的所有项元素与beautifulsoup

时间:2011-11-22 01:05:23

标签: python rss beautifulsoup

从RSS Feed中,您如何获得每个标记内的所有内容?

示例输入(简化):

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Test</title>
<item>
  <title>Hello world1</title>
  <comments>Hi there</comments>
  <pubDate>Tue, 21 Nov 2011 20:10:10 +0000</pubDate>
</item>
<item>
  <title>Hello world2</title>
  <comments>Good afternoon</comments>
  <pubDate>Tue, 22 Nov 2011 20:10:10 +0000</pubDate>
</item>
<item>
  <title>Hello world3</title>
  <comments>blue paint</comments>
  <pubDate>Tue, 23 Nov 2011 20:10:10 +0000</pubDate>
</item>
</channel>
</rss>

我需要一个python函数来获取这个RSS文件(我现在正在使用beautifulsoup),并且有一个遍历每个项目的循环。我需要一个变量,其中包含每个中所有内容的字符串。

第一个循环结果示例:

<title>Hello world1</title>
<comments>Hi there</comments>
<pubDate>Tue, 21 Nov 2011 20:10:10 +0000</pubDate>

这段代码让我得到了第一个结果,但是如何获得下一个结果呢?

html_data = BeautifulSoup(xml)
print html_data.channel.item

1 个答案:

答案 0 :(得分:3)

由于这是XML,请使用BeautifulStoneSoup

import BeautifulSoup
doc = BeautifulSoup.BeautifulStoneSoup(xml)
for item in doc.findAll('item'):
    for elt in item:
        if isinstance(elt,BeautifulSoup.Tag):
            print(elt)

以下是你如何使用lxml做同样的事情(由于某些原因我发现它更容易使用):

import lxml.etree as ET
doc = ET.fromstring(xml)
for item in doc.xpath('//item'):
    for elt in item.xpath('descendant::*'):
        print(ET.tostring(elt))
相关问题