2010-03-31 39 views
2

我正在尝试通过python处理美味的RSS源。这里有一个例子:通过xml.dom.minidom处理RSS/RDF

... 
    <item rdf:about="http://weblist.me/"> 
    <title>WebList - The Place To Find The Best List On The Web</title> 
    <dc:date>2009-12-24T17:46:14Z</dc:date> 
    <link>http://weblist.me/</link> 
    ... 
    </item> 
    <item rdf:about="http://thumboo.com/"> 
    <title>Thumboo! Free Website Thumbnails and PHP Script to Generate Web Screenshots</title> 
    <dc:date>2006-10-24T18:11:32Z</dc:date> 
    <link>http://thumboo.com/</link> 
... 

相关的代码是:

def getText(nodelist): 
    rc = "" 
    for node in nodelist: 
     if node.nodeType == node.TEXT_NODE: 
      rc = rc + node.data 
    return rc 

dom = xml.dom.minidom.parse(file) 
items = dom.getElementsByTagName("item") 
for i in items: 
    title = i.getElementsByTagName("title") 
    print getText(title) 

我认为这会打印出每一个标题,而是我得到基本上得到空白输出。我确信我在做一些愚蠢的错误,但不知道是什么?

+1

你有没有试过http://feedparser.org/? – badp 2010-03-31 07:58:28

+1

这是一个简单的RSS源,它与RDF无关。 XML中有一些属性是从RDF名称空间导入的,但Feed仍然是RSS源。请更正您问题的标题以反映此问题。 – 2010-03-31 09:00:50

+0

'getElementsByTagName'返回'ELEMENT_NODE'列表,所以每次检查到'TEXT_NODE'失败。我没有测试,但我很确定这一点。 – 2010-03-31 09:10:01

回答

4

您正在将title节点传递给getText,其nodeType不是node.TEXT_NODE。你必须循环遍历,而不是你的getText方法节点的所有子:

def getTextSingle(node): 
    parts = [child.data for child in node.childNodes if child.nodeType == node.TEXT_NODE] 
    return u"".join(parts) 

def getText(nodelist): 
    return u"".join(getTextSingle(node) for node in nodelist) 

更妙的是,呼吁getTextSingle从而确保node.TEXT_NODE类型的连续孩子合并成一个单一node.TEXT_NODE之前调用node.normalize()

+0

首先,这个作品 - 谢谢! 我正在学习Python和试图环绕我的头: [child.data儿童在node.childNodes如果child.nodeType == node.TEXT_NODE] 我相信这是类似于: 的孩子node.childNodes: if child.nodeType == node.TEXT_NODE 但是不明白child.data在哪里发挥作用。 (我想它是在文档中,但无法在docs.python.org上找到相关信息) – Bill 2010-04-05 06:10:12

+0

该构造称为*列表理解*。你可以在这里阅读更多关于它的信息:http://docs.python.org/tutorial/datastructures.html#list-comprehensions – 2010-04-05 10:16:36