gpt4 book ai didi

python - 如何实现 python 来查找 xml 标签之间的值?

转载 作者:太空宇宙 更新时间:2023-11-03 12:22:32 25 4
gpt4 key购买 nike

我正在使用谷歌网站检索天气信息,我想在 XML 标签之间查找值。以下代码给出了一个城市的天气状况,但我无法获得其他参数,例如温度,如果可能的话,请解释代码中隐含的拆分功能的工作原理:

import urllib

def getWeather(city):

#create google weather api url
url = "http://www.google.com/ig/api?weather=" + urllib.quote(city)

try:
# open google weather api url
f = urllib.urlopen(url)
except:
# if there was an error opening the url, return
return "Error opening url"

# read contents to a string
s = f.read()

# extract weather condition data from xml string
weather = s.split("<current_conditions><condition data=\"")[-1].split("\"")[0]

# if there was an error getting the condition, the city is invalid


if weather == "<?xml version=":
return "Invalid city"

#return the weather condition
return weather

def main():
while True:
city = raw_input("Give me a city: ")
weather = getWeather(city)
print(weather)

if __name__ == "__main__":
main()

谢谢

最佳答案

USE

A

PARSER

您不能使用正则表达式解析 XML,所以不要尝试。这是一个 start to finding an XML parser in Python .这是一个 good site for learning about parsing XML in Python .

更新:鉴于有关 PyS60 的新信息,这里是 documentation for using XML来自诺基亚的网站。

更新 2:@Nas Banov 请求了示例代码,所以这里是:

import urllib

from xml.parsers import expat

def start_element_handler(name, attrs):
"""
My handler for the event that fires when the parser sees an
opening tag in the XML.
"""
# If we care about more than just the temp data, we can extend this
# logic with ``elif``. If the XML gets really hairy, we can create a
# ``dict`` of handler functions and index it by tag name, e.g.,
# { 'humidity': humidity_handler }
if 'temp_c' == name:
print "The current temperature is %(data)s degrees Celsius." % attrs

def process_weather_conditions():
"""
Main logic of the POC; set up the parser and handle resource
cleanup.
"""
my_parser = expat.ParserCreate()
my_parser.StartElementHandler = start_element_handler

# I don't know if the S60 supports try/finally, but that's not
# the point of the POC.
try:
f = urllib.urlopen("http://www.google.com/ig/api?weather=30096")
my_parser.ParseFile(f)
finally:
f.close()

if __name__ == '__main__':
process_weather_conditions()

关于python - 如何实现 python 来查找 xml 标签之间的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3063319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com