我正在尝试从一个网站中解析。我被卡住了。我将在下面提供XML。它来自一个webiste。我有两个问题。从网站读取xml的最好方法是什么,然后我在深入研究xml以获得所需的速率时遇到了困难。
我需要返回的数字是Base:OBS_VALUE 0.12
到目前为止,我所拥有的:
from xml.dom import minidom
import urllib
document = ('http://www.newyorkfed.org/markets/omo/dmm/fftoXML.cfm?type=daily''r')
web = urllib.urlopen(document)
get_web = web.read()
xmldoc = minidom.parseString(document)
ff_DataSet = xmldoc.getElementsByTagName('ff:DataSet')[0]
ff_series = ff_DataSet.getElementsByTagName('ff:Series')[0]
for line in ff_series:
price = line.getElementsByTagName('base:OBS_VALUE')[0].firstChild.data
print(price)来自webiste的XML代码:
-<Header> <ID>FFD</ID>
<Test>false</Test>
<Name xml:lang="en">Federal Funds daily averages</Name> <Prepared>2013-05-08</Prepared>
<Sender id="FRBNY"> <Name xml:lang="en">Federal Reserve Bank of New York</Name>
<Contact>
<Name xml:lang="en">Public Information Web Team</Name> <Email>ny.piwebteam@ny.frb.org</Email>
</Contact>
</Sender>
<!--ReportingBegin></ReportingBegin-->
</Header>
<ff:DataSet> -<ff:Series TIME_FORMAT="P1D" DISCLAIMER="G" FF_METHOD="D" DECIMALS="2" AVAILABILITY="A">
<ffbase:Key>
<base:FREQ>D</base:FREQ>
<base:RATE>FF</base:RATE>
<base:MATURITY>O</base:MATURITY>
<ffbase:FF_SCOPE>D</ffbase:FF_SCOPE>
</ffbase:Key>
<ff:Obs OBS_CONF="F" OBS_STATUS="A">
<base:TIME_PERIOD>2013-05-07</base:TIME_PERIOD>
<base:OBS_VALUE>0.12</base:OBS_VALUE>发布于 2013-05-08 21:52:22
如果你想坚持使用xml.dom.minidom,试试这个...
from xml.dom import minidom
import urllib
url_str = 'http://www.newyorkfed.org/markets/omo/dmm/fftoXML.cfm?type=daily'
xml_str = urllib.urlopen(url_str).read()
xmldoc = minidom.parseString(xml_str)
obs_values = xmldoc.getElementsByTagName('base:OBS_VALUE')
# prints the first base:OBS_VALUE it finds
print obs_values[0].firstChild.nodeValue
# prints the second base:OBS_VALUE it finds
print obs_values[1].firstChild.nodeValue
# prints all base:OBS_VALUE in the XML document
for obs_val in obs_values:
print obs_val.firstChild.nodeValue但是,如果您想使用lxml,请使用underrun的解决方案。此外,您的原始代码也有一些错误。您实际上是在尝试解析document变量,即网址。您需要解析从网站返回的xml,在您的示例中是get_web变量。
发布于 2013-05-08 21:39:55
看看你的代码:
document = ('http://www.newyorkfed.org/markets/omo/dmm/fftoXML.cfm?type=daily''r')
web = urllib.urlopen(document)
get_web = web.read()
xmldoc = minidom.parseString(document)我不确定您的文档是否正确,除非您想要http://www.newyorkfed.org/markets/omo/dmm/fftoXML.cfm?type=dailyr,因为这就是您将得到的结果(本例中的parens组和相邻列出的字符串会自动连接)。
在此之后,您需要做一些工作来创建get_web,但是在下一行中不会使用它。相反,您可以尝试解析您的document,它是url…
除此之外,我完全建议您使用ElementTree,最好使用lxml的ElementTree (http://lxml.de/)。此外,lxml的etree解析器接受一个类似文件的对象,该对象可以是urllib对象。如果您这样做了,那么在整理完文档的其余部分之后,您可以这样做:
from lxml import etree
from io import StringIO
import urllib
url = 'http://www.newyorkfed.org/markets/omo/dmm/fftoXML.cfm?type=daily'
root = etree.parse(urllib.urlopen(url))
for obs in root.xpath('/ff:DataSet/ff:Series/ff:Obs'):
price = obs.xpath('./base:OBS_VALUE').text
print(price)https://stackoverflow.com/questions/16441823
复制相似问题