python找指定内容_在Python中-解析响应xml并查找特定的文本值

I'm new to python and I'm having a particularly difficult time working with xml and python. The situation I have is this, I'm trying to count the number of times a word appears in an xml document. Simple enough, but the xml document is a response from a server. Is it possible to do this without writing to a file? It would be great trying to do it from memory.

Here is a sample xml code:

Info

aldfj

Text I want to count

Here is what I have in python

import urllib2

import StringIO

import xml.dom.minidom

from xml.etree.ElementTree import parse

usock = urllib.urlopen('http://www.example.com/file.xml')

xmldoc = minidom.parse(usock)

print xmldoc.toxml()

Past This point I have tried using StringIO, ElementTree, and minidom to no success and I have gotten to a point where I'm not sure what else to do.

Any help would be greatly appreciated

解决方案

If you are just trying to count the number of times a word appears in an XML document, just read the document as a string and do a count:

import urllib2

data = urllib2.urlopen('http://www.example.com/file.xml').read()

print data.count('foobar')

Otherwise, you can just iterate through the tags you are looking for:

from xml.etree import cElementTree as ET

xml = ET.fromstring(urllib2.urlopen('http://www.example.com/file.xml').read())

for data in xml.getiterator('data'):

# do something with

data.text

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值