今天学习了爬虫基本的访问数据,分析数据的方法
用到了json和urllib2两个模块
urllib2的主要功能是访问网站,从网站上面获取基本的数据。
获得的数据基本是以字符串形式进行保存
然后通过json模块对获得的字符串进行处理,处理成为能够被python所处理的数据结构。
今天遇到的最大问题是有关python中汉字编码的问题
似乎python2.x要想用汉字对比成功必须要用cp936进行编码
# -*- coding: cp936 -*-
import urllib2
import json
from city import city
#city是一个已存在的文件 包含对应城市的访问编码
cityname=raw_input('你想查哪个城市的天气?\n')
citycode=city.get(cityname)
if citycode:
url=('http://www.weather.com.cn/data/cityinfo/%s.html'%citycode)
content=urllib2.urlopen(url).read()
data=json.loads(content)
weatherinfo=data['weatherinfo']
maxtemp=weatherinfo['temp2']
mintemp=weatherinfo['temp1']
weather=weatherinfo['weather']
print '%s %s~%s'%(weather,mintemp,maxtemp)