在Python中分析xml时出错

2024-10-01 22:42:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析:http://www.codespot.blogspot.in/atom.xml?redirect=false&start-index=1&max-results=500

问题是:

  1. 我必须将xml存储在一个文件中,以便ElementTree对其进行解析。如何避免它,只解析GET请求的字符串响应?

  2. 虽然我这么做了,但为了得到所有的头衔,它仍然不起作用:

    f = open('output.xml','wb+')
        f.write(r.content)
        f.close()
        tree = ""
        with open('output.xml', 'rt') as f:
            tree = ElementTree.parse(f)
            print tree
            root = tree.getroot()
            for elem in tree.iter():
                print elem.tag, elem.attrib
            for atype in tree.findall('title'):
                print atype.contents
    

Tags: intreehttpforoutputwwwxmlopen
1条回答
网友
1楼 · 发布于 2024-10-01 22:42:38
import urllib2
from xml.etree import cElementTree as ET
conn = urllib2.urlopen("http://www.codespot.blogspot.in/atom.xml?redirect=false&start-index=1&max-results=500")
myins=ET.parse(conn)
for elem in myins.findall('{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}title'):
    print elem.text

或者找到标题和内容:

for elem in myins.findall('{http://www.w3.org/2005/Atom}entry'):
    print elem.find('{http://www.w3.org/2005/Atom}title').text ## this will be the title
    print elem.find('{http://www.w3.org/2005/Atom}content').text ## this will be the content

相关问题 更多 >

    热门问题