由于新项目需要用到国家统计局得到行政区划代码,原先的行政区划代码都是在一页里面的,现在放在链接里面嵌套了,所以今天心血来潮写了个爬虫,把行政区划爬下来,最新的区划是2020.02.25发布的数据,废话不多说,直接上代码。
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
FileStream fs = new FileStream("b.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
try
{
var webGet = new HtmlWeb();
webGet.OverrideEncoding = Encoding.GetEncoding("GB2312");
string index = string.Format("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2019/");
var document = webGet.Load(index);
var metaTags = document.DocumentNode.SelectNodes("//tr[@class='provincetr']//a");
foreach (HtmlNode sheng in metaTags)//省
{
try
{
sw.WriteLine(sheng.InnerText + "\t"+ sheng.Attributes["href"].Value.Replace(".html","").PadRight(12,'0'));
Console.WriteLine(sheng.InnerText + "\t");
//+ sheng.Attributes["href"].Value
string shengurl = index + sheng.Attributes["href"].Value;
var shidocument = webGet.Load(shengurl);
var shi = shidocument.DocumentNode.SelectNodes("//tr[@class='citytr']//a");
for (int shii = 0; shii < shi.Count; shii += 2)//市
{
sw.WriteLine("\t" + shi[shii + 1].InnerText + "\t" + shi[shii].InnerText);
Console.WriteLine("\t" + shi[shii + 1].InnerText + "\t" + shi[shii].InnerText);
//shi[i + 1].Attributes["href"].Value
string shiurl = index + shi[shii].Attributes["href"].Value;
var xiandocument = webGet.Load(shiurl);
var xian = xiandocument.DocumentNode.SelectNodes("//tr[@class='countytr']//a");
if(xian==null)
xian = xiandocument.DocumentNode.SelectNodes("//tr[@class='towntr']//a");
for (int xiani = 0; xiani < xian.Count; xiani += 2)//县
{
sw.WriteLine("\t\t" + xian[xiani + 1].InnerText + "\t" + xian[xiani].InnerText);
Console.WriteLine("\t\t" + xian[xiani + 1].InnerText + "\t" + xian[xiani].InnerText);
}
}
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
continue;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
sw.Flush();
sw.Close();
fs.Close();
这里面有个坑的地方就是东莞市他么的县区,直接乡镇街道了,所以节点选取做了判断。内部可以拓展到村庄街道,因为项目精确到县区就可以了 所以后面就没写了。
最后放上爬取好的文件