爬一下国家统计局行政区划代码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/ 对数据进行的特殊处理: 将直辖市中的 “市辖区” 与 “县” 合并到区域 将 “省直辖县级行 ...
随机推荐
- java获取机器IP地址常用方法
private String getHostIP(){ Enumeration<NetworkInterface> allNetInterfaces = null; String resu ...
- 任意N个不同数的逆序对平均值
在学习数据结构的时候看到了以下定理: 但是老师并没有解释,本着钻研的精神决定搞清楚为什么是这个数. 在百度 google一番之后并没有找到,决定自己试着证明. 最开始走了一些弯路,但突然灵光一闪很容易 ...
- 《重构》的读书笔记–方法列表
第5章 重构列表 5.1 重构的记录格式103 5.2 寻找引用点105 5.3 这些重构手法有多成熟106 第6章 重新组织函数 6.1 (P110)Extract Method(提炼函数) 6.2 ...
- 老白关于rac性能调优的建议(10gRAC)
RAC应用设计方面需要在底层做很有设计.虽然ORACLE的售前人员总是说RAC的扩展性是透明的,只要把应用分到不同的节点,就可以平滑的扩展系统能力了.而事实上,RAC的CACHE FUSION机制决定 ...
- Redis5.0.4复制
redis的复制很简单,由于资源限制,本例中采用两台虚拟机,每台虚拟机安装两个redis实例,共四个来测试 一.安装redis https://www.cnblogs.com/qq931399960/ ...
- DRF缓存
对于现在的动态网站来讲,所有的界面展示都是通过客户端请求服务端,服务端再去请求数据库,然后将请求到的数据渲染后返回给客户端.用户每次访问页面都需要去请求数据库,如果同时有多个人访问的话,对于我们的数据 ...
- Python学习步骤如何安排?
一.清楚学习目标 无论是学习什么知识,都要有一个对学习目标的清楚认识. 只有这样才能朝着目标持续前进,少走弯路,从学习中得到不断的提升,享受python学习计划的过程. 二.基本python 知识学习 ...
- Java的properties文件读取和属性修改
package Test; import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileO ...
- js检查身份证号是否正确
转的,比较完善的验证身份证号的代码 /* check(ID)验证身份证号码 返回值:0 : "是正确的身份证号" 1 : "身份证校验不符合求和模11=1这个等式&quo ...
- Django1-HTTP协议介绍
何为http协议(Hypertext Transfer Protocol,超文本传输协议)? 所谓协议,就是指双方遵循的规范.http协议,就是浏览器和服务器之间进行“沟通”的一种规范.我们在看空间, ...