从国家统计局采集最新行政区划分

  最近一新项目要用到国内行政区划数据,bing了一下,已有网友提供sql版本数据下载,但在本地查看数据不够新,至少我老家所在市2010年改名儿了这数据也看不到。所以说呢还是自己动手丰衣足食。 使用了JSON.NET

  1、

   

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
 
namespace DivisonsOfPRC
{
    /// <summary>
    /// 演示代码,不建议在生产环境使用,请搜HttpClient
    /// </summary>
    public class Http
    {
        public string GET(string url)
        {
            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
            hwr.Method = "GET";
            hwr.CookieContainer = new CookieContainer();
            hwr.Accept = "*/*";
            hwr.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN");
 
            hwr.Referer = "http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/";
            hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
 
            HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.UTF8;
            StreamReader readStream = new StreamReader(receiveStream, encode);
 
            String linesOfHTML = readStream.ReadToEnd();
            //System.Console.WriteLine(linesOfHTML);
            //System.Console.ReadKey();
 
            receiveStream.Close();
            response.Close();
            readStream.Close();
            return linesOfHTML;
        }
    }
}

 

生成JSON.NET

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
 
namespace DivisonsOfPRC
{
    /// <summary>
    /// 演示代码,不建议在生产环境使用,请搜HttpClient
    /// </summary>
    public class Http
    {
        public string GET(string url)
        {
            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
            hwr.Method = "GET";
            hwr.CookieContainer = new CookieContainer();
            hwr.Accept = "*/*";
            hwr.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN");
 
            hwr.Referer = "http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/";
            hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
 
            HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.UTF8;
            StreamReader readStream = new StreamReader(receiveStream, encode);
 
            String linesOfHTML = readStream.ReadToEnd();
            //System.Console.WriteLine(linesOfHTML);
            //System.Console.ReadKey();
 
            receiveStream.Close();
            response.Close();
            readStream.Close();
            return linesOfHTML;
        }
    }
}

测试用例:

 

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
 
namespace DivisonsOfPRC
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] directs = new string[] { "北京市", "天津市", "上海市", "重庆市" };
            Http http = new Http();
            //1.采集html到本地
            string html = http.GET("http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201401/t20140116_501070.html");
            //System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "dop.html", html, Encoding.UTF8);
             
            //2.分析html
            //可以用HtmlAgilePack找到行政区划数据的核心html
            //我这里就不演示HAP怎么使用了,咱简单点儿,就用字符串分析截取
            int startIndex = html.LastIndexOf("TRS_Editor");
            startIndex = html.IndexOf("<p class=\"", startIndex);
            html = html.Substring(startIndex);
            html = html.Substring(0, html.IndexOf("</div>"));
 
            //真正分析省市区逻辑
            string[] lines = html.Split(new string[] { "</p>" }, StringSplitOptions.RemoveEmptyEntries);
            string code = null, name= null,line = null;
             
            List<Node> nodes = new List<Node>();
            Node PrevCity = null;
            Node PrevProvince = null;
            for (int i = 0; i < lines.Length; i++)
            {
                Node nod = new Node();
                line = ExtractHtml(lines[i], "align=\"justify\">", "");
                code = line.Substring(0, line.IndexOf("&"));
                name = line.Substring(line.LastIndexOf(";")+1).Trim();
                nod.code = code;
                nod.name = name;
 
                int timesOfSpaceOccure = CountString(line, "&nbsp;");
                nod.spaces = timesOfSpaceOccure;
                if (timesOfSpaceOccure == 3)
                {
                    nodes.Add(nod);
                    PrevProvince = nod;
                    PrevCity = null;
                }
                else
                {
                    if (timesOfSpaceOccure > PrevProvince.spaces)
                    {
                        //下一级别
                        if (PrevCity != null && timesOfSpaceOccure > PrevCity.spaces)
                        {
                            if (PrevCity.cell == null)
                            {
                                PrevCity.cell = new List<Node>();
                            }
                            PrevCity.cell.Add(nod);
                        }
                        else
                        {
                            //
                            if (PrevProvince.cell == null)
                            {
                                PrevProvince.cell = new List<Node>();
                            }
                            PrevProvince.cell.Add(nod);
                            PrevCity = nod;
                        }
                    }
                }
                 
            }
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            string json2 = JsonConvert.SerializeObject(nodes, Newtonsoft.Json.Formatting.None, settings);
            System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "data.js", json2, Encoding.UTF8);
        }
 
        static string ExtractHtml(string source, string prefix, string suffix)
        {
            if (string.IsNullOrEmpty(source))
            {
                return null;
            }
            int startIndex = source.IndexOf(prefix);
            if (startIndex == -1)
            {
                return string.Empty;
            }
            startIndex = startIndex + prefix.Length;
            int endIndex = source.Length;
            if (!string.IsNullOrEmpty(suffix))
            {
                endIndex = source.IndexOf(suffix, startIndex);
                if (endIndex == -1)
                {
                    //suffix not found
                    return string.Empty;
                }
            }
            return source.Substring(startIndex, endIndex - startIndex);
            //return null;
        }
 
        static int CountString(string source, string search)
        {
            int count = 0;
            int startIndex = 0;
            startIndex = source.IndexOf(search);
            while (startIndex != -1)
            {
                startIndex = source.IndexOf(search, startIndex + search.Length);
                count++;
            }
            return count;
        }
    }
}

  

 

留下备用

转载于:https://www.cnblogs.com/long2008/p/4153644.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
国家统计局抓取的地图省市区划代码和城划代码(最新2020/06/03),共596071条数据。来源于国家统计局http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2019/。 数据结构: CREATE TABLE `area` ( `areaid` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `area_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `fatherid` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `area_type` int(255) DEFAULT NULL COMMENT '区域代码:\r\n100 :城镇,110:城区,111 :主城区,112 :城乡结合区,120 :镇区,121 :镇中心区,122:镇乡结合区,123:特殊区域200 :乡村,210:乡中心区,220:村庄\r\n\r\n', `is_delete` int(255) DEFAULT '0', PRIMARY KEY (`areaid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 部数据: INSERT INTO `area` VALUES ('110000000000','北京市',NULL,NULL,0); INSERT INTO `area` VALUES ('110100000000','市辖区','110000000000',NULL,0); INSERT INTO `area` VALUES ('110101000000','东城区','110100000000',NULL,0); INSERT INTO `area` VALUES ('110101001000','东华门街道','110101000000',NULL,0); INSERT INTO `area` VALUES ('110101001001','多福巷社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001002','银闸社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001005','东厂社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001006','智德社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001007','南池子社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001008','黄图岗社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001009','灯市口社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001010','正义路社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001011','甘雨社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001013','台基厂社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001014','韶九社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101001015','王府井社区居委会','110101001000',111,0); INSERT INTO `area` VALUES ('110101002000','景山街道','110101000000',NULL,0); INSERT INTO `area` VALUES ('110101002001','隆福寺社区居委会','110101002000',111,0); INSERT INTO `area` VALUES ('110101002002','吉祥社区居

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值