获取开心网的省份、城市及学校列表
2009年10月28日 | 4:01 下午分类:python |
目前在做公司的一个SNS项目,其中有一个模块就是添加教育经历,整个流程与开心网基本一致。
开心网中的城市列表及学校列表返回格式是json的,c#中不大好处理json,不能“智能”地将json字符串转换为一个“对象”。
php处理json异常简单,直接用json_decode就行了。
这里是用python实现的,用到了第三方的一个json模块,调用后直接将json转成了list
运行时效果如下:
web上
#!/usr/bin/env python
#coding=utf-8
import sys
import os
import json
import urllib2
import time
provinces = []
citys = []
areas = []
def GetProvince():
'''获取省及直辖市'''
url = 'http://www.kaixin001.com/interface/suggestlocation.php?type=0'
request = urllib2.urlopen(url)
jsonData = request.read()
d = json.read(jsonData)
global provinces
for a in d:
provinces.append(a['id'])
print 'get:'+a['name']
if int(a['type']) == -1: #获取直辖市
GetArea(a['id'],3)
else:
GetCity(1,a['id'])
def GetCity(typeid,provinceid):
'''获取城市'''
url = 'http://www.kaixin001.com/interface/suggestlocation.php?type=%s&id=%s' % (typeid,provinceid)
global citys
request = urllib2.urlopen(url)
jsonData = request.read()
d = json.read(jsonData)
for a in d:
citys.append(a['id'])
print 'get:'+a['name']
GetArea(a['id'])
def GetArea(cityid,typeid = 2):
'''获取区级县级地名'''
url = 'http://www.kaixin001.com/interface/suggestlocation.php?type=%s&id=%s' % (typeid, cityid)
global areas
request = urllib2.urlopen(url)
jsonData = request.read()
d = json.read(jsonData)
for a in d:
areas.append(a['id'])
print 'get:'+a['name']
def GetSchool(schooltype,cityid):
'''获取学校'''
url = 'http://www.kaixin001.com/interface/suggestlocation.php?type=%s&id=%s' % (schooltype,cityid)
request = urllib2.urlopen(url)
jsonData = request.read()
d = json.read(jsonData)
for a in d:
print 'get'+a['name']
if __name__=='__main__':
GetProvince()
print u'共有省份或直辖市: %d ' % len(provinces)
print u'共有城市: %d ' % len(citys)
print u'共有区县: %d ' % len(areas)
citys.extend(areas)
#大学
for pid in provinces:
time.sleep(1)
GetSchool(4,pid)
#高中初中及技校
for cid in citys:
for i in (5,6,7):
GetSchool(i,cid)
转载时务必以超链接形式标明文章原始出处和作者信息。




生成数据库放在本地比较好~之前也写过采集省市数据的