لا يمكن تحليل XML بشكل فعال باستخدام Python
-
28-09-2019 - |
سؤال
import urllib
import xml.etree.ElementTree as ET
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()
tree=ET.parse(s)
current= tree.find("current_condition/condition")
condition_data = current.get("data")
weather = condition_data
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()
يعطي خطأ ، أردت بالفعل العثور على قيم من علامات موقع Google Weather XML
المحلول
بدلاً من
tree=ET.parse(s)
محاولة
tree=ET.fromstring(s)
أيضا ، طريقك إلى البيانات التي تريدها غير صحيح. يجب أن يكون: الطقس/current_conditions/الحالة
هذا يجب أن يعمل:
import urllib
import xml.etree.ElementTree as ET
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()
tree=ET.fromstring(s)
current= tree.find("weather/current_conditions/condition")
condition_data = current.get("data")
weather = condition_data
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)
نصائح أخرى
سأعطي نفس الإجابة هنا التي قمت بها في تعليقي على سؤالك السابق. في المستقبل ، يرجى تحديث السؤال الحالي بدلاً من نشر سؤال جديد.
أنا آسف - لم أقصد أن الكود الخاص بي سيعمل تمامًا كما تريد. الخطأ الخاص بك هو أن S عبارة عن سلسلة وأن تحليل ملف أو كائن يشبه الملف. لذلك ، "شجرة = et.parse (f)" قد تعمل بشكل أفضل. أود أن أقترح قراءة elementtree API حتى تفهم الوظائف التي استخدمتها أعلاه في الممارسة العملية. آمل أن يساعد ذلك ، واسمحوا لي أن أعرف إذا كان يعمل.
لا تنتمي إلى StackOverflow