爬一下国家统计局行政区划代码C#
目前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#的更多相关文章
- 使用java爬取国家统计局的12位行政区划代码
前言: 本文基于j2ee的原始url进行都写,解析指定内容时也是使用很傻的形式去查找指定格式的字符串来实现的. 更优雅的方式是可以使用apache的HttpClient和某些文档模型将HTML字符串构 ...
- 【转】纯JS省市区三级联动(行政区划代码更新至2015-9-30)
本文代码实现的功能是省市区三级联动下拉列表,纯Javascript,网上已有很多这方面的代码.但是作为一个新手,这是我的第一篇CSDN博客,发此文的目的主要是学习交流,希望看到的朋友发现有什么不对的地 ...
- Python爬虫 - 爬取百度html代码前200行
Python爬虫 - 爬取百度html代码前200行 - 改进版, 增加了对字符串的.strip()处理 源代码如下: # 改进版, 增加了 .strip()方法的使用 # coding=utf-8 ...
- python爬虫,使用BeautifulSoup解析爬出来的HTML代码时报错
UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for thi ...
- 行政区划代码(JSON版本)2018年8月
字段:regioncode //行政区划代码 regionname //行政区划名称 pcode //行政区划上一级代码 [{ "REGIONCODE": "11000 ...
- 爬取百度页面代码写入到文件+web请求过程解析
一.爬取百度页面代码写入到文件 代码示例: from urllib.request import urlopen #导入urlopen包 url="http://www.baidu.com& ...
- Winform开发框架之字典管理模块的更新,附上最新2013年全国最新县及县以上行政区划代码sql脚本
在很多项目里面,字典管理是必备的项目模块,而这个又是比较通用的功能,因此可以单独做成一个通用字典管理,例如这个模块,可以通过集成的方式,使用在我的<Winform开发框架>.<WCF ...
- python2爬取国家统计局全国省份城市区街道信息
工作中,再次需要python,发现python用得好 ,真的可以节省很多人力,先说我的需求,需要做一个类似像支付宝添加收货地址时,选择地区的功能,需要详细到街道信息,也就是4级联动,如右图.首先需要的 ...
- 最新县及县以上行政区划代码JSON数据(截止2015年9月30日)含经纬度数据
数据来源(国家统计局):http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/ 对数据进行的特殊处理: 将直辖市中的 “市辖区” 与 “县” 合并到区域 将 “省直辖县级行 ...
随机推荐
- Spring JPA 使用@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 自动生成时间和修改者
JPA Audit 在spring jpa中,支持在字段或者方法上进行注解@CreatedDate.@CreatedBy.@LastModifiedDate.@LastModifiedBy,从字面意思 ...
- RocketMQ知识整理与总结
1.架构 RocketMQ的master broker与master broker没有任何消息通讯,nameserver之间也同样没有消息通信 MQ历史 由数据结构队列发展而来 MQ使用场景 异 ...
- Codeception 实战
Codeception 测试 Php 代码 一.一句话概述 使用 cc 进行单元测试,保证现有代码质量,为以后维护与重构提供支撑. 二.目标 安装配置 cc 编写测试代码,简化开发与最大化稳定性和可维 ...
- 阿狸V任务页面爬取数据解析
需求: 爬取:https://v.taobao.com/v/content/video 所有主播详情页信息 首页分析 分析可以得知数据是通过ajax请求获取的. 分析请求头 详情页分析 详情页和详情页 ...
- ASP.NET基础知识汇总之WebConfig自定义节点详细介绍
之前介绍过Webconfig的具体知识ASP.NET基础知识汇总之WebConfig各节点介绍.今天准备封装一个ConfigHelper类,涉及到了自定义节点的东东,平时虽然一直用,但也没有系统的总结 ...
- 解决在使用gensim.models.word2vec.LineSentence加载语料库时报错 UnicodeDecodeError: 'utf-8' codec can't decode byte......的问题
在window下使用gemsim.models.word2vec.LineSentence加载中文维基百科语料库(已分词)时报如下错误: UnicodeDecodeError: 'utf-8' cod ...
- 第二章 Python基本图形绘制
2.1 深入理解Python语言 Python语言是通用语言 Python语言是脚本语言 Python语言是开源语言 Python语言是跨平台语言 Python语言是多模型语言 Python的特点与优 ...
- 08 Django REST Framework 解决前后端分离项目中的跨域问题
01-安装模块 pip install django-cors-headers 02-添加到INSTALL_APPS中 INSTALLED_APPS = ( ... 'corsheaders', .. ...
- [Alpha阶段]无人转会申请
Alpha阶段无人转会申请 大家好,我们是Water_T团队.我们团队在Alpha阶段较好完成了预期目标,团队成员合作愉快,氛围良好,配合默契,且完成的产品在alpha阶段中是用户可互动.可使用的功能 ...
- (三)jdk8学习心得之方法引用
三.方法引用 https://www.jianshu.com/p/c9790ba76cee 这边博客写的很好,可以首先阅读,在这里感谢这篇文章的博主. 1. 格式 调用者::调用者具备的方法名 2. ...