基于Python的爬虫项目一——城市天气
这个是一个非常simple的东西,二话不说,直接上代码喽。
主要用到了urllib.request库和json解析,个人感觉比urllib2好用。
下面是代码,个人感觉实在没什么可以值得讲解的。
PS.城市代码字典自己搞喽,又是文本处理之类的。
# encoding=UTF-8
import urllib.request
import json
def next():
pl=input('继续1 退出2:\n')
if(pl=='1'):
print('1')
beg()
if(pl=='2'):
print("结束")
exit
else:
print("wrong")
def getcity(x):
xx={'北京':'101010100','洛阳':'101180901'}
if x in xx:
return xx[x]
else:
print('wrong')
def beg():
city=input('请输入城市名:\n')
citycode=101010100
citycode=getcity(city)
url=("http://www.weather.com.cn/data/sk/%s.html"%(str(citycode)))
content=urllib.request.urlopen(url).read()
data=json.loads(content.decode())
result=data['weatherinfo']
print('城市:',result['city'],'温度:',result['temp'],'风向:',result['WD'])
next()
beg()