目前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. springCloud feign使用/优化总结

    基于springCloud Dalston.SR3版本 1.当接口参数是多个的时候 需要指定@RequestParam 中的value来明确一下. /** * 用户互扫 * @param uid 被扫 ...

  2. React---入门(1)

    React是什么? React 是一个用于构建用户界面的 JAVASCRIPT 库. React 特点 1.声明式设计 −React采用声明范式,可以轻松描述应用. 2.高效 −React通过对DOM ...

  3. centos7的内核区别

    最近重新搭建环境准备测试一些东西,在网上随意下载了一个镜像,名字叫做:CentOS-7-i386-Everything-1810 下载完之后开始做实验安装软件的时候发现一直报错:[Errno 14] ...

  4. nginx 常见正则匹配符号表示

    1.^: 匹配字符串的开始位置: 2. $:匹配字符串的结束位置: 3..*: .匹配任意字符,*匹配数量0到正无穷: 4.\. 斜杠用来转义,\.匹配 . 特殊使用方法,记住记性了: 5.(值1|值 ...

  5. openstack 2019/4/28

    官网参考地址:https://docs.openstack.org/keystone/queens/install/index-rdo.html (但愿能看懂) 环境:这个部分解释如何按示例架构配置控 ...

  6. 使用try-with-resources优雅的关闭IO流

    Java类库中包括许多必须通过调用close方法来手工关闭的资源.例如InputStream.OutputStream和java.sql.Connection.客户端经常会忽略资源的关闭,造成严重的性 ...

  7. 使用.Net Core Mvc +SqlSugar +Autofac+AutoMapper+....

    开源地址:https://github.com/AjuPrince/Aju.Carefree 目前用到了 SqlSugar.Dapper.Autofac.AutoMapper.Swagger.Redi ...

  8. Linux下网络配置与修改Centos7为列

    一.基础知识 手动绑定: 命令 一般是临时的修改,重启后失效,如:ifconfig.route.ip addr等. 修改配置文件 修改文件配置,永久有效,但是可能不能立即生效,需要重启服务 (serv ...

  9. Map the Debris 轨道周期

    返回一个数组,其内容是把原数组中对应元素的平均海拔转换成其对应的轨道周期. 原数组中会包含格式化的对象内容,像这样 {name: 'name', avgAlt: avgAlt}. 至于轨道周期怎么求, ...

  10. MYSQL Statement violates GTID consistency: Updates to non-transactional tables can only be done in either autocommitted statements or single-statement transactions, and never in the same statement as

    [2019-04-21 10:17:20] [ERROR] [org.hibernate.engine.jdbc.spi.SqlExceptionHelper:144] Statement viola ...