使用 beautifulsoup 解析来自 RSS feed 的所有子项元素

dee*_*ell 2 python rss beautifulsoup

如何从 RSS 提要中获取每个项目标签内所有内容的字符串?

输入示例(简化):

<?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>
Run Code Online (Sandbox Code Playgroud)

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

第一个循环结果示例:

<title>Hello world1</title>
<comments>Hi there</comments>
<pubDate>Tue, 21 Nov 2011 20:10:10 +0000</pubDate>
Run Code Online (Sandbox Code Playgroud)

这段代码给了我第一个结果,但是我如何获得接下来的所有结果呢?

html_data = BeautifulSoup(xml)
print html_data.channel.item
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 5

使用BeautifulStoup 4

import bs4 as bs
doc = bs.BeautifulSoup(xml, 'xml')
for item in doc.findAll('item'):
    for elt in item:
        if isinstance(elt, BeautifulSoup.Tag):
            print(elt)
Run Code Online (Sandbox Code Playgroud)

下面是如何使用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))
Run Code Online (Sandbox Code Playgroud)

  • BeautifulStoup 4 中已弃用“BeautifulStoneSoup”;将 'xml' 作为第二个参数传递: `BeautifulSoup(text,'xml')` http://www.crummy.com/software/BeautifulSoup/bs4/doc/#xml (4认同)