37,719
社区成员
发帖
与我相关
我的任务
分享
city = ['四川','成都','温江']
def getWeatherForCity(city,city_code=''):
if city_code == '':
content = getContent('http://m.weather.com.cn/data5/city.xml')
arr = content.split(',')
for i in arr:
if city[0] == i.split('|')[1]:
city_code = i.split('|')[0]
print city[0] + '的编码是:' + city_code
del city[0]
break
getWeatherForCity(city,city_code)
else:
content = getContent('http://m.weather.com.cn/data5/city%s.xml' % city_code)
arr = content.split(',')
for i in arr:
if city[0] == i.split('|')[1]:
city_code = i.split('|')[0]
print city[0] + '的编码是:' + city_code
del city[0]
break
if city.__len__() > 0:
getWeatherForCity(city,city_code)
else:
result = getContent('http://www.weather.com.cn/data/cityinfo/%s.html' % ('101' + city_code))
print result
return result
def getContent(url):
return urllib2.urlopen(url).read()
print getWeatherForCity(city)
return getWeatherForCity(city,city_code)
递归返回上一层时结果没继续往上返回
getWeatherForCity(city,city_code)
改成:
return getWeatherForCity(city,city_code)
import urllib.request as urllib2
city = ['四川','成都','温江']
def getWeatherForCity(city,city_code=''):
if city_code == '':
content = getContent('http://m.weather.com.cn/data5/city.xml')
print(content)
arr = content.split(',')
for i in arr:
if city[0] == i.split('|')[1]:
city_code = i.split('|')[0]
print(city[0] + '的编码是:' + city_code)
del city[0]
break
getWeatherForCity(city,city_code)
else:
content = getContent('http://m.weather.com.cn/data5/city%s.xml' % city_code)
arr = content.split(',')
for i in arr:
if city[0] == i.split('|')[1]:
city_code = i.split('|')[0]
print(city[0] + '的编码是:' + city_code)
del city[0]
break
if city.__len__() > 0:
getWeatherForCity(city,city_code)
else:
result = getContent('http://www.weather.com.cn/data/cityinfo/%s.html' % ('101' + city_code))
print(result)
return result
def getContent(url):
return urllib2.urlopen(url).readall().decode('utf-8')
print(getWeatherForCity(city))
我的python是3.3,把read改成了readall,完了再decode一下,程序返回正常。。
分别是 27,2701,270104