获取开心网的省份、城市及学校列表

in python

目前在做公司的一个SNS项目,其中有一个模块就是添加教育经历,整个流程与开心网基本一致。

开心网中的城市列表及学校列表返回格式是json的,c#中不大好处理json,不能“智能”地将json字符串转换为一个“对象”。

php处理json异常简单,直接用json_decode就行了。

这里是用python实现的,用到了第三方的一个json模块,调用后直接将json转成了list

运行时效果如下:

ScreenShot00053

web上

ScreenShot00054

#!/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)
10 Comments

10 Comments

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

  2. 参考:http://www.json.org/

    JSON的C# 版本包应该是有的,几乎所有的语言都有。

    • c#里关于json的第三方组件还是挺多的
      但它到底没有动态语言这么方便,至少在将json串转为object时,都需要先定义这个对象。
      这也是语言的特性所决定的。

  3. 盛大要上SNS了?[face:15]

  4. 年初的时候投过盛大sns项目的简历,后来由于工作确定了而没有去面试。要不然还真有可能和你成为同事呢。

  5. 幻想曲,有没有打包成MySql数据库的文件,发给我一份,谢谢!
    我的邮箱是:wuweiqin@126.com

  6. 幻想曲,能否把城市,学校的数据库打包发我一份 谢谢哈 email :zdfgng@126.com

  7. 请问一下,开心网中的城市列表及学校列表返回格式是json的,这个URL地址http://www.kaixin001.com/interface/suggestlocation.php是在哪里找到的?我现在想用PY对我的照片进行操作,但是找不到这样的JSON格式的照片URL,能否帮忙?我的邮箱是sd5921054@163.com,谢谢

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>