- 帖子
- 1
- 精华
- 0
- 积分
- 7
- 阅读权限
- 10
- 注册时间
- 2018-6-1
- 最后登录
- 2018-6-26
|
本帖最后由 猪猪猪猪 于 2018-6-1 19:31 编辑
使用mac os vim,py3
在网上查询了半天,不太理解json的使用方法,索性撇开json,仅使用urllib,写出来之后,发现获取的北京地区的代号是错误的?但是其他的一些地区是可以查询的,比如武汉,南京等,不知道是什么原因,希望能有大神解惑!
citynumget.py- import urllib.request
- response = urllib.request.urlopen('http://m.weather.com.cn/data3/city.xml')
- html = response.read().decode()
- datas1 = html.split(',')
- city = []
- for data in datas1:
- data = data.split('|')
- city.append(data[0])
- city1 = []
- for i in city:
- response = urllib.request.urlopen('http://m.weather.com.cn/data3/city%s.xml'%(i))
- html = response.read().decode()
- datas2 = html.split(',')
- for data in datas2:
- data = data.split('|')
- city1.append(data[0])
- city2 = []
- for i in city1:
- response = urllib.request.urlopen('http://m.weather.com.cn/data3/city%s.xml'%(i))
- html = response.read().decode()
- city2.append(html)
- city3 = ','.join(city2)
- citynum = open('citynum.txt','w')
- citynum.write(city3)
- citynum.close()
复制代码 查询天气.py- import urllib.request
- f = open('citynum.txt')
- city = f.read()
- f.close()
- city1 = city.split(',')
- citynum = {}
- for i in city1:
- data = i.split('|')
- citynum[data[1]] = data[0]
- print('请输入要查询天气的城市:')
- city = input()
- response = urllib.request.urlopen('http://www.weather.com.cn/data/cityinfo/101%s.html'%(citynum[city]))
- html = response.read().decode()
- html = html.split('{')#乱想的笨办法,将读取的文本写入字典
- html = html[-1].split('}')
- html = html[0]
- html = html.split('"')
- html = ''.join(html)
- html = html.split(',')
- weather = {}
- for i in html:
- i = i.split(':')
- weather[i[0]] = i[1]
- print('%s当前天气为%s,气温为%s~%s'%(weather['city'],weather['weather'],weather['temp1'],weather['temp2']))
复制代码 PS:第一次写这么长的代码,第一次发帖,好激动
——————————————————————
补充:看完之后的课程之后发现原来抓数据的时候漏掉了一步。。。但是这样都还能查就比较稀奇了 |
|