目前NBS上有2015-2018四个年度的代码信息,写一个控制台程序爬一下县级行政区下的代码。

使用HttpWebRequest+HttpWebResponse获取html,使用HtmlAgilityPack类库解析HTML。

使用POST请求,请求头带Cookie信息,否则会被反爬机制挡死,返回“请开启JavaScript并刷新该页”。

县级URL Request获取数据的同时记录Response的Cookie信息,在请求镇级数据时,请求头发送此cookie。

“省-地-县-乡 ”与“省-县(地)-乡” 的URL长度不同,根据长度判断URL正确性时需注意,也许还有其他可能,暂未发现。

主方法

  class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("\r\n----获取县级行政区乡、村二级区划代码");
Console.WriteLine("----数据年份有:");
Console.ResetColor();
Cursor.WriteAt("A、2018", , );
Cursor.WriteAt("B、2017", , );
Cursor.WriteAt("C、2016", , );
Cursor.WriteAt("D、2015", , );
Input: Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine();
Console.WriteLine("----请输入一个年份代码(回车提交):");
Console.ResetColor();
char chr = Convert.ToChar( Console.ReadLine().ToLower()[]);
if ((int)chr >= &&(int)chr <= )
{
string year = string.Empty;
switch (chr)
{
case 'a':
year = ""; break;
case 'b':
year = ""; break;
case 'c':
year = ""; break;
default:
year = ""; break;
}
System.Diagnostics.Process.Start($"http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/{year}");
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("浏览器已加载区划代码起始页,请进入县级行政单位页面,复制url,粘贴到下面(回车提交):");
}
else
goto Input;
Console.ResetColor();
string cityurl = Console.ReadLine();
if (cityurl.Length != && cityurl.Length!=)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("url有误,请确认是县级行政单位页面,重新复制链接,粘贴到下面:");
Console.ResetColor();
cityurl = Console.ReadLine();
}
try
{
Console.ForegroundColor = ConsoleColor.Magenta;
Func<object, List<TownInfo>> func = new Func<object, List<TownInfo>>(GetTownInfos);
Task<List<TownInfo>> task = new Task<List<TownInfo>>(func, cityurl);
task.Start();
task.Wait();
if (task.Status == TaskStatus.RanToCompletion && task.Result.Count > )
{ List<VillageInfo> villageInfos = new List<VillageInfo>();
foreach (var item in task.Result)
{
//把乡镇信息写入村级列表,实现乡镇信息输出
VillageInfo villageInfo_town = new VillageInfo(item.Code, "", item.Name);
villageInfos.Add(villageInfo_town);
Func<object, List<VillageInfo>> func1 = new Func<object, List<VillageInfo>>(GetVillageInfos);
Task<List<VillageInfo>> task1 = new Task<List<VillageInfo>>(func1, item.Href);
task1.Start();
task1.Wait();
if (task1.Status == TaskStatus.RanToCompletion)
{
villageInfos.AddRange(task1.Result);
}
}
foreach (var item1 in villageInfos)
{
Console.WriteLine($"{item1.Name.Trim()}\t{item1.Cls.Trim()}\t{item1.Code.Trim()}");
}
}
else
{ Console.WriteLine("乡镇列表获取失败!"); } }
catch (Exception)
{
throw new Exception("");
}
Console.ReadKey();
}
static string cookies = "AD_RS_COOKIE=20082854; wzws_cid=453a2d88181321410de83ba7eedaba3a141eb61ee7488027b6ab07a66054605e99e886827afa72708ce170398ea2fdfeec55455a7c0be8e779694026255f2166";
//获取乡镇级信息列表
static List<TownInfo> GetTownInfos(object cityurl)
{
List<TownInfo> townInfos = new List<TownInfo>();
HttpGetHelper httpGetHelper = new HttpGetHelper() { Url =(string) cityurl, ContentType = "text/html; charset=gb2312", Encode = Encoding.GetEncoding(),RequestMethod="post"};
//HtmlAgilityPack类库解析HTML
HtmlDocument document = new HtmlDocument();
document.LoadHtml(httpGetHelper.GetHtml(,ref cookies));
//string html = httpGetHelper.GetHtml(ref cookies);
//路径里"//"表示从根节点开始查找,两个斜杠‘//’表示查找所有childnodes;一个斜杠'/'表示只查找第一层的childnodes(即不查找grandchild);点斜杠"./"表示从当前结点而不是根结点开始查找
HtmlNodeCollection htmlNodes = document.DocumentNode.SelectNodes("//tr[@class='towntr']");
foreach (var node in htmlNodes)
{
HtmlNodeCollection htmlNodes1 = node.SelectNodes("./td");
HtmlNode htmlNodeHref = node.SelectSingleNode(".//a[@href]");
HtmlAttribute htmlAttribute = htmlNodeHref.Attributes["href"];
TownInfo townInfo = new TownInfo(htmlNodes1[].InnerText, htmlNodes1[].InnerText,
(cityurl as string).Substring(, (cityurl as string).LastIndexOf('/') + ) + htmlAttribute.Value);
townInfos.Add(townInfo);
}
return townInfos;
}
//获取村级信息列表
static List<VillageInfo> GetVillageInfos(object townurl)
{
List<VillageInfo> villageInfos = new List<VillageInfo>();
HttpGetHelper httpGetHelper = new HttpGetHelper() { Url = (string)townurl, ContentType = "text/html; charset=gb2312", Encode = Encoding.GetEncoding(), RequestMethod = "post"};
HtmlDocument document = new HtmlDocument();
document.LoadHtml(httpGetHelper.GetHtml(,ref cookies));
//string html = httpGetHelper.GetHtml(ref cookies);
HtmlNodeCollection htmlNodes = document.DocumentNode.SelectNodes("//tr[@class='villagetr']");
foreach (var node in htmlNodes)
{
HtmlNodeCollection htmlNodes1 = node.SelectNodes(".//td");
VillageInfo villageInfo = new VillageInfo(htmlNodes1[].InnerText,htmlNodes1[].InnerText,htmlNodes1[].InnerText);
villageInfos.Add(villageInfo);
}
return villageInfos;
}
}

辅助类/结构

   internal class Cursor
{
const int origRow = ;
const int origCol = ;
public static void WriteAt(string s, int c, int r)
{
Console.SetCursorPosition(origCol + c, origRow + r);
Console.Write(s);
}
}
//乡镇信息结构 编码、名称、超链
struct TownInfo
{
string code;
public string Code{ get { return code; } }
string name;
public string Name{get { return name; } }
string href;
public string Href { get { return href; } }
public TownInfo (string code,string name,string href)
{
this.code = code;
this.name = name;
this.href = href;
}
}
//村信息结构 编码、城乡划分类,名称
struct VillageInfo
{
string code;
public string Code{ get { return code; } }
string cls;
public string Cls{ get { return cls; } }
string name;
public string Name{ get { return name; } }
public VillageInfo(string code,string cls,string name)
{
this.code = code;
this.cls = cls;
this.name = name;
}
}

获取HTML

     public class HttpGetHelper
{
string url = string.Empty;
public string Url
{
set { url = value; }
} int timeOut=*;
public int Timeout
{
set { timeOut = value; }
} string contentType= "text/html;charset=utf-8";
public string ContentType
{
set { contentType = value; }
} string userAgent= "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 ";
public string UserAgent
{
set { userAgent = value; }
} Encoding encode=Encoding.UTF8;
public Encoding Encode
{
set { encode = value; }
}
string request_Method = "get";
public string RequestMethod
{
set { request_Method = value; }
}
/// <summary>
/// get html content
/// </summary>
/// <param name="cls">town=1;village=2</param>
/// <param name="cookies">if cls=1 then ref cookies</param>
/// <returns></returns>
public string GetHtml(int cls,ref string cookies)
{
string html = string.Empty;
try
{
if (url!=string.Empty)
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Timeout = this.timeOut;
request.ContentType = this.contentType;
request.UserAgent = this.userAgent;
request.Headers.Add(HttpRequestHeader.Cookie, cookies);
request.Method = request_Method;
using (HttpWebResponse response =request.GetResponse()as HttpWebResponse)
{
if (response.StatusCode==HttpStatusCode.OK)
{//如果是县级url,则记录cookie
if (cls==)
{
CookieCollection cookieCollection = response.Cookies;
foreach (Cookie item in cookieCollection)
{
cookies = item.Name + "=" + item.Value + ";";
}
cookies.Remove(cookies.Length - );
} using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), encode))
{
html = streamReader.ReadToEnd();
streamReader.Close();
}
}
}
}
}
catch (Exception)
{
throw new Exception($"GetHtml失败,url:{url}");
}
return html;
}
}

爬一下国家统计局行政区划代码C#的更多相关文章

  1. 使用java爬取国家统计局的12位行政区划代码

    前言: 本文基于j2ee的原始url进行都写,解析指定内容时也是使用很傻的形式去查找指定格式的字符串来实现的. 更优雅的方式是可以使用apache的HttpClient和某些文档模型将HTML字符串构 ...

  2. 【转】纯JS省市区三级联动(行政区划代码更新至2015-9-30)

    本文代码实现的功能是省市区三级联动下拉列表,纯Javascript,网上已有很多这方面的代码.但是作为一个新手,这是我的第一篇CSDN博客,发此文的目的主要是学习交流,希望看到的朋友发现有什么不对的地 ...

  3. Python爬虫 - 爬取百度html代码前200行

    Python爬虫 - 爬取百度html代码前200行 - 改进版,  增加了对字符串的.strip()处理 源代码如下: # 改进版, 增加了 .strip()方法的使用 # coding=utf-8 ...

  4. python爬虫,使用BeautifulSoup解析爬出来的HTML代码时报错

    UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for thi ...

  5. 行政区划代码(JSON版本)2018年8月

    字段:regioncode //行政区划代码  regionname //行政区划名称 pcode //行政区划上一级代码 [{ "REGIONCODE": "11000 ...

  6. 爬取百度页面代码写入到文件+web请求过程解析

    一.爬取百度页面代码写入到文件 代码示例: from urllib.request import urlopen #导入urlopen包 url="http://www.baidu.com& ...

  7. Winform开发框架之字典管理模块的更新,附上最新2013年全国最新县及县以上行政区划代码sql脚本

    在很多项目里面,字典管理是必备的项目模块,而这个又是比较通用的功能,因此可以单独做成一个通用字典管理,例如这个模块,可以通过集成的方式,使用在我的<Winform开发框架>.<WCF ...

  8. python2爬取国家统计局全国省份城市区街道信息

    工作中,再次需要python,发现python用得好 ,真的可以节省很多人力,先说我的需求,需要做一个类似像支付宝添加收货地址时,选择地区的功能,需要详细到街道信息,也就是4级联动,如右图.首先需要的 ...

  9. 最新县及县以上行政区划代码JSON数据(截止2015年9月30日)含经纬度数据

    数据来源(国家统计局):http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/ 对数据进行的特殊处理: 将直辖市中的 “市辖区” 与 “县” 合并到区域 将 “省直辖县级行 ...

随机推荐

  1. 一条查询sql的执行流程和底层原理

    1.一条查询SQL执行流程图 2.查询SQL执行流程之发送SQL请求 (1)客户端按照Mysql通信协议将SQL发送到服务端,SQL到达服务端后,服务端会单起一个线程执行SQL. (2)执行时Mysq ...

  2. RuntimeException和Exception区别

    1.java将所有的错误封装为一个对象,其根本父类为Throwable, Throwable有两个子类:Error和Exception. 2.Error是Throwable 的子类,用于指示合理的应用 ...

  3. Delphi 数据转换

    指针转换   Pointer——string string:=PChar(Pointer);{ Pointer指向的数据要以#0结尾.使用System.AllocMem(Size)分配的内存是用#0填 ...

  4. asyncio 基础用法

    asyncio 基础用法 python也是在python 3.4中引入了协程的概念.也通过这次整理更加深刻理解这个模块的使用 asyncio 是干什么的? asyncio是Python 3.4版本引入 ...

  5. CentOS 安装 ceph 单机版(luminous版本)

    一.环境准备 CentOS Linux release 7.4.1708 (Core)一台,4块磁盘(sda.sdb,.sdc.sdd) 192.168.27.130 nceph 二.配置环境 1.修 ...

  6. python标准日志模块logging及日志系统设计

    最近写一个爬虫系统,需要用到python的日志记录模块,于是便学习了一下. python的标准库里的日志系统从Python2.3开始支持.只要import logging这个模块即可使用.如果你想开发 ...

  7. eplan图框制作

    1. 首先,新建一个原理图项目 2. 新建图框.选择“工具”→“主数据”→“图框”→“新建” 在“文件名”中输入文件名,保存. 3.添加新建图框属性选项.选中“新建符号*”,添加选项 4. 设置图框的 ...

  8. 滴滴 CTO 架构师 业务 技术 战役 时间 赛跑 超前 设计

    滴滴打车CTO张博:生死战役,技术和时间赛跑-CSDN.NEThttps://www.csdn.net/article/2015-06-25/2825058-didi 滴滴出行首席架构师李令辉:业务的 ...

  9. Centos6.5 pppoe-server

    [root@localhost network-scripts]# rpm -q rp-pppoepackage rp-pppoe is not installed ----------------- ...

  10. MongoDB 4.0.* 远程连接及用户名密码认证登陆配置——windows