草庐IT

python - 如何在 Python 和 LXML 中解析 XML?

coder 2024-06-26 原文

这是我的项目:我正在使用 RRDTool 从 WeatherBug 绘制天气数据图表。我需要一种简单、高效的方法来从 WeatherBug 下载天气数据。我使用的是一个非常低效的 bash-script-scraper,但后来转向了 BeautifulSoup。性能太慢(它在 Raspberry Pi 上运行)所以我需要使用 LXML。

我目前拥有的:

from lxml import etree
doc=etree.parse('weather.xml')
print doc.xpath("//aws:weather/aws:ob/aws:temp")

但是我收到一条错误消息。 Weather.xml 是这样的:

<?xml version="1.0" encoding="UTF-8"?>

<aws:weather xmlns:aws="http://www.aws.com/aws">
  <aws:api version="2.0"/>
  <aws:WebURL>http://weather.weatherbug.com/PA/Tunkhannock-weather.html?ZCode=Z5546&amp;Units=0&amp;stat=TNKCN</aws:WebURL>
  <aws:InputLocationURL>http://weather.weatherbug.com/PA/Tunkhannock-weather.html?ZCode=Z5546&amp;Units=0</aws:InputLocationURL>
  <aws:ob>
    <aws:ob-date>
      <aws:year number="2013"/>
      <aws:month number="1" text="January" abbrv="Jan"/>
      <aws:day number="11" text="Friday" abbrv="Fri"/>
      <aws:hour number="10" hour-24="22"/>
      <aws:minute number="26"/>
      <aws:second number="00"/>
      <aws:am-pm abbrv="PM"/>
      <aws:time-zone offset="-5" text="Eastern Standard Time (USA)" abbrv="EST"/>
    </aws:ob-date>
    <aws:requested-station-id/>
    <aws:station-id>TNKCN</aws:station-id>
    <aws:station>Tunkhannock HS</aws:station>
    <aws:city-state zipcode="18657">Tunkhannock, PA</aws:city-state>
    <aws:country>USA</aws:country>
    <aws:latitude>41.5663871765137</aws:latitude>
    <aws:longitude>-75.9794464111328</aws:longitude>
    <aws:site-url>http://www.tasd.net/highschool/index.cfm</aws:site-url>
    <aws:aux-temp units="&amp;deg;F">-100</aws:aux-temp>
    <aws:aux-temp-rate units="&amp;deg;F">0</aws:aux-temp-rate>
    <aws:current-condition icon="http://deskwx.weatherbug.com/images/Forecast/icons/cond013.gif">Cloudy</aws:current-condition>
    <aws:dew-point units="&amp;deg;F">40</aws:dew-point>
    <aws:elevation units="ft">886</aws:elevation>
    <aws:feels-like units="&amp;deg;F">41</aws:feels-like>
    <aws:gust-time>
      <aws:year number="2013"/>
      <aws:month number="1" text="January" abbrv="Jan"/>
      <aws:day number="11" text="Friday" abbrv="Fri"/>
      <aws:hour number="12" hour-24="12"/>
      <aws:minute number="18"/>
      <aws:second number="00"/>
      <aws:am-pm abbrv="PM"/>
      <aws:time-zone offset="-5" text="Eastern Standard Time (USA)" abbrv="EST"/>
    </aws:gust-time>
    <aws:gust-direction>NNW</aws:gust-direction>
    <aws:gust-direction-degrees>323</aws:gust-direction-degrees>
    <aws:gust-speed units="mph">17</aws:gust-speed>
    <aws:humidity units="%">98</aws:humidity>
    <aws:humidity-high units="%">100</aws:humidity-high>
    <aws:humidity-low units="%">61</aws:humidity-low>
    <aws:humidity-rate>3</aws:humidity-rate>
    <aws:indoor-temp units="&amp;deg;F">77</aws:indoor-temp>
    <aws:indoor-temp-rate units="&amp;deg;F">-1.1</aws:indoor-temp-rate>
    <aws:light>0</aws:light>
    <aws:light-rate>0</aws:light-rate>
    <aws:moon-phase moon-phase-img="http://api.wxbug.net/images/moonphase/mphase01.gif">0</aws:moon-phase>
    <aws:pressure units="&quot;">30.09</aws:pressure>
    <aws:pressure-high units="&quot;">30.5</aws:pressure-high>
    <aws:pressure-low units="&quot;">30.08</aws:pressure-low>
    <aws:pressure-rate units="&quot;/h">-0.01</aws:pressure-rate>
    <aws:rain-month units="&quot;">0.11</aws:rain-month>
    <aws:rain-rate units="&quot;/h">0</aws:rain-rate>
    <aws:rain-rate-max units="&quot;/h">0.12</aws:rain-rate-max>
    <aws:rain-today units="&quot;">0.09</aws:rain-today>
    <aws:rain-year units="&quot;">0.11</aws:rain-year>
    <aws:temp units="&amp;deg;F">41</aws:temp>
    <aws:temp-high units="&amp;deg;F">42</aws:temp-high>
    <aws:temp-low units="&amp;deg;F">29</aws:temp-low>
    <aws:temp-rate units="&amp;deg;F/h">-0.9</aws:temp-rate>
    <aws:sunrise>
      <aws:year number="2013"/>
      <aws:month number="1" text="January" abbrv="Jan"/>
      <aws:day number="11" text="Friday" abbrv="Fri"/>
      <aws:hour number="7" hour-24="07"/>
      <aws:minute number="29"/>
      <aws:second number="53"/>
      <aws:am-pm abbrv="AM"/>
      <aws:time-zone offset="-5" text="Eastern Standard Time (USA)" abbrv="EST"/>
    </aws:sunrise>
    <aws:sunset>
      <aws:year number="2013"/>
      <aws:month number="1" text="January" abbrv="Jan"/>
      <aws:day number="11" text="Friday" abbrv="Fri"/>
      <aws:hour number="4" hour-24="16"/>
      <aws:minute number="54"/>
      <aws:second number="19"/>
      <aws:am-pm abbrv="PM"/>
      <aws:time-zone offset="-5" text="Eastern Standard Time (USA)" abbrv="EST"/>
    </aws:sunset>
    <aws:wet-bulb units="&amp;deg;F">40.802</aws:wet-bulb>
    <aws:wind-speed units="mph">3</aws:wind-speed>
    <aws:wind-speed-avg units="mph">1</aws:wind-speed-avg>
    <aws:wind-direction>S</aws:wind-direction>
    <aws:wind-direction-degrees>163</aws:wind-direction-degrees>
    <aws:wind-direction-avg>SE</aws:wind-direction-avg>
  </aws:ob>
</aws:weather>

我用了http://www.xpathtester.com/test测试我的 xpath,它在那里工作。但我收到错误消息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lxml.etree.pyx", line 2043, in lxml.etree._ElementTree.xpath (src/lxml/lxml.etree.c:47570)
  File "xpath.pxi", line 376, in lxml.etree.XPathDocumentEvaluator.__call__ (src/lxml/lxml.etree.c:118247)
  File "xpath.pxi", line 239, in lxml.etree._XPathEvaluatorBase._handle_result (src/lxml/lxml.etree.c:116911)
  File "xpath.pxi", line 224, in lxml.etree._XPathEvaluatorBase._raise_eval_error (src/lxml/lxml.etree.c:116728)
lxml.etree.XPathEvalError: Undefined namespace prefix

这对我来说都是非常新的 -- Python、XML 和 LXML。我想要的只是观察到的时间和温度。

我的问题是否与所有内容前面的 aws: 前缀有关?这到底是什么意思?

非常感谢您提供的任何帮助!

最佳答案

这个问题全都“与 aws: prefix in front of everything 有关”;它是您必须定义的命名空间前缀。这很容易实现,如:

print doc.xpath('//aws:weather/aws:ob/aws:temp', 
                namespaces={'aws': 'http://www.aws.com/aws'})[0].text

命名空间前缀到值之间的这种映射的需要记录在 http://lxml.de/xpathxslt.html 中.

关于python - 如何在 Python 和 LXML 中解析 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14289990/

有关python - 如何在 Python 和 LXML 中解析 XML?的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  7. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  8. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  9. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  10. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

随机推荐