C#网页爬虫抓取行政区划
借鉴C#网页爬虫抓取行政区划,从国家统计局获取了最新行政区域数据。
以下为代码贴片:
数据库类:
public class City {public decimal ID { get; set; }public string Name { get; set; }public string Code { get; set; }public string Org_Level { get; set; }public string ParentCode { get; set; }public decimal ParentID { get; set; }public string Contry { get; set; }public string Loc_x { get; set; }public string Loc_y { get; set; }}
获取网页帮助类:
public class HttpHelper {private static ILog log = log4net.LogManager.GetLogger(typeof(HttpHelper));public static string DownloadHtml(string url,Encoding encod) {string html = string.Empty;try {//设置请求参数HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;request.Timeout = 10 * 1000;//10s超时request.ContentType = "text/html;charset=utf-8";request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";//获取结果using(HttpWebResponse resp = request.GetResponse() as HttpWebResponse) {if(resp.StatusCode != HttpStatusCode.OK) {log.Fatal(string.Format("抓取{0}地址返回失败,response.StatusCode = {1}",url,resp.StatusCode));} else {try {StreamReader sr = new StreamReader(resp.GetResponseStream(),encod);html = sr.ReadToEnd();sr.Close();} catch(Exception e) {log.Fatal(string.Format("DownLoadHtml抓取html{0}保存失败",url),e);}}}} catch(Exception e) {if(e.Message.Equals("远程服务器返回错误:(306)。")) {}log.Fatal(e);} finally {}return html;}}
数据库保存帮助类:
public class SQLHelper {/// 一个有效的数据库连接对象 /// 命令类型(存储过程,命令文本或其它.) /// T存储过程名称或T-SQL语句 /// SqlParamter参数数组 /// 返回影响的行数 public static int ExecuteNonQueryForCity(List<City> cityList) {int count = 0;//string dbConnectStr = System.Configuration.ConfigurationSettings.AppSettings["DBContext"].ToString();var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBContext"].ConnectionString;using(SqlConnection connection = new SqlConnection(connectionString)) {if(connection.State != ConnectionState.Open) {connection.Open();}// 创建SqlCommand命令,并进行预处理 using(SqlCommand cmd = new SqlCommand()) {cmd.Connection = connection;cmd.CommandText = "insert into base_city(ID,name,Code,Contry,Loc_x,Loc_y,Org_Level,ParentCode,ParentID,state) values(@ID,@name,@Code,@Contry,@Loc_x,@Loc_y,@Org_Level,@ParentCode,@ParentID,@state)";foreach(var city in cityList) {try {if(string.IsNullOrEmpty(city.Name))city.Name = "";if(string.IsNullOrEmpty(city.Code))city.Code = "";if(string.IsNullOrEmpty(city.Contry))city.Contry = "";if(string.IsNullOrEmpty(city.Loc_x))city.Loc_x = "";if(string.IsNullOrEmpty(city.Loc_y))city.Loc_y = "";if(string.IsNullOrEmpty(city.Org_Level))city.Org_Level = "";if(string.IsNullOrEmpty(city.ParentCode))city.ParentCode = "";cmd.Parameters.Add(new SqlParameter("@ID",city.ID));cmd.Parameters.Add(new SqlParameter("@name",city.Name));cmd.Parameters.Add(new SqlParameter("@Code",city.Code));cmd.Parameters.Add(new SqlParameter("@Contry",city.Contry)); cmd.Parameters.Add(new SqlParameter("@Loc_x",city.Loc_x)); cmd.Parameters.Add(new SqlParameter("@Loc_y",city.Loc_y));cmd.Parameters.Add(new SqlParameter("@Org_Level",city.Org_Level));cmd.Parameters.Add(new SqlParameter("@ParentCode",city.ParentCode));cmd.Parameters.Add(new SqlParameter("@ParentID",city.ParentID));cmd.Parameters.Add(new SqlParameter("@state","1"));// Finally, execute the command int retval = cmd.ExecuteNonQuery();if(retval == 0) {Console.WriteLine("插入错误:");}count += retval;} catch(Exception e) {Console.WriteLine("插入错误:" + e.Message);}// 清除参数,以便再次使用. cmd.Parameters.Clear();}}connection.Close();}return count;}}
抓取数据:
public class 省市县数据抓取 {private ILog log = log4net.LogManager.GetLogger(typeof(省市县数据抓取));public const string UrlStr = "http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201703/t20170310_1471429.html";public List<City> SaveList = new List<City>();public 省市县数据抓取() {try {log.Info("抓取数据");string HtmlStr = HttpHelper.DownloadHtml(UrlStr,Encoding.UTF8);HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();doc.LoadHtml(HtmlStr);//string goodsListPath = "//*[@id='J_goodsList']";//HtmlNode goodsListNode = doc.DocumentNode.SelectSingleNode(goodsListPath);string liPath = "//p[@class='MsoNormal']";HtmlNodeCollection goodsNodeCollection = doc.DocumentNode.SelectNodes(liPath);City c = new City() { ID=1,Name = "全国",Code = "100000",Contry = "China",Org_Level = "1"};SaveList.Add(c);foreach(var item in goodsNodeCollection) {var firstNode = item.FirstChild;if(firstNode.Name == "b")GetProvince(item);else if(firstNode.InnerText == " ") {GetCity(item);} else if(firstNode.InnerText == " ") {GetCounty(item);}}} catch(Exception e) {log.Info("last child code:" + SaveList.Last().Code);log.Info(e);throw (e);}}private void GetCounty(HtmlNode item) {City c = new City();c.Code = item.ChildNodes[1].InnerText.Replace(" ","").Trim();c.Name = item.ChildNodes[2].InnerText.Trim();c.Org_Level = "4";c.ID = SaveList.Last().ID + 1;var pc = SaveList.Last(i => i.Org_Level == "3");c.ParentCode = pc.Code;c.ParentID = pc.ID;c.Contry = "China";//if(c.Name == "市辖区")// return;SaveList.Add(c);}private void GetCity(HtmlNode item) {City c = new City();c.Code = item.ChildNodes[1].InnerText.Replace(" ","").Trim();c.Name = item.ChildNodes[2].InnerText.Trim(); c.Org_Level = "3";c.ID = SaveList.Last().ID + 1;var pc = SaveList.Last(i => i.Org_Level == "2");c.ParentCode = pc.Code;c.ParentID = pc.ID;c.Contry = "China";SaveList.Add(c);}private void GetProvince(HtmlNode item) {City c = new City();c.Code = item.ChildNodes[0].FirstChild.InnerText.Replace(" ","").Trim();c.Name = item.ChildNodes[1].FirstChild.InnerText.Trim();c.Org_Level = "2";c.ID = SaveList.Last().ID + 1;var pc = SaveList.Last(i => i.Org_Level == "1");c.ParentCode = pc.Code;c.ParentID = pc.ID;c.Contry = "China";SaveList.Add(c);}public void Save() {log.Info("保存数据");SQLHelper.ExecuteNonQueryForCity(SaveList);}}
全国 Org_Level =1
省 Org_Level =2
市 Org_Level =3
县 Org_Level =4
SaveList 首先添加了一个全国属性城市,Org_Level =1
因为网页数据读取是从省->市->县 ->省->市->县 这样循环读取的,所以在获取省、市、县的父级时,可以直接从SaveList 获取最后一个上一级别的对象即可
执行类:
省市县数据抓取 CityCatch = new 省市县数据抓取();
CityCatch.Save();
获取的数据如下:
C#网页爬虫抓取行政区划相关推荐
- java爬虫抓取行政区划_7-爬虫爬API抓取行政区划(urllib).ipynb
{ "cells": [ { "cell_type": "markdown", "metadata": {}, &quo ...
- python 网页爬虫抓取 自动化测试之phantomjs使用详解
PhantomJS俗称为:无界面的浏览器.PhantomJS是一个基于webkit的JavaScript API.它使用QtWebKit作为它核心浏览器的功能,使用webkit来编译解释执行JavaS ...
- Java爬虫抓取网页
Java爬虫抓取网页 原作者:hebedich 原文链接 下面直接贴代码: import java.io.BufferedReader; import java.io.InputStreamRead ...
- python——爬虫实现网页信息抓取
首先实现关于网页解析.读取等操作我们要用到以下几个模块 import urllib import urllib2 import re 我们可以尝试一下用readline方法读某个网站,比如说百度 de ...
- python抓取图片_Python3简单爬虫抓取网页图片
现在网上有很多python2写的爬虫抓取网页图片的实例,但不适用新手(新手都使用python3环境,不兼容python2), 所以我用Python3的语法写了一个简单抓取网页图片的实例,希望能够帮助到 ...
- 如何用python抓取文献_浅谈Python爬虫技术的网页数据抓取与分析
浅谈 Python 爬虫技术的网页数据抓取与分析 吴永聪 [期刊名称] <计算机时代> [年 ( 卷 ), 期] 2019(000)008 [摘要] 近年来 , 随着互联网的发展 , 如何 ...
- java抓取页面表格_用java实现爬虫抓取网页中的表格数据功能源码
[实例简介] 使用java代码基于MyEclipse开发环境实现爬虫抓取网页中的表格数据,将抓取到的数据在控制台打印出来,需要后续处理的话可以在打印的地方对数据进行操作.包解压后导入MyEclipse ...
- java爬虫抓取网页数据论坛_Java爬虫抓取网页
Java爬虫抓取网页原作者:hebedich 原文链接 下面直接贴代码: import java.io.BufferedReader; import java.io.InputStreamReade ...
- node爬虫,抓取网页数据
node爬虫,抓取网页数据 1.什么是爬虫? 抓取信息或者数据的程序或者是脚本 2.通过node实现对网页数据的抓取. 安装插件 request,处理请求(此包以被弃用) npm i request ...
最新文章
- IBM Watson:用人工智能提升美国零售业消费体验
- 复杂问题需要系统思维
- 三菱plc编程实例3000_三菱PLC十字路口的红绿灯编程实例
- 关于不过洋节的通知_蟠桃宫小学关于平安夜、圣诞节安全教育告家长通知书
- Failed to execute goal on project xxx: Could not resolve dependencies for project com
- bbs php redis,LAMP+redis搭建discuz论坛
- css3如何实现倒影效果
- 面试中的常见14种算法套路
- hadoop2.x HDFS快照介绍
- note_maven的pom.xml部分配置说明
- mysql意外关机_MySQL服务器意外关机-无法启动多实例
- django外键和多数据库应用
- python网课推荐-python网课什么平台好
- PHP设置脚本最大执行时间的三种方法
- 使用PHP来简单的创建一个RPC服务
- MongoDB数据库操作和程序基础文档
- 【无标题】提示用户输入用户名,然后再提示输入密码,如果用户名 是“admin”并且密码是“88888”,则提示正确,否则,如果 用户名不是admin还提示用户用户名不存在,如果用户名是
- 5750G GT540M显卡游戏蓝屏的终极解决方法!
- 激光雷达在汽车上的应用史
- java word转html乱码怎么办,poi导出word 乱码 poi word转html 乱码
热门文章
- 从I4GL迁移到EGL
- mysql删除函数sql_SQLServer之删除函数
- MySQL万字总结!超详细!
- iPhonexr安兔兔html5测试,iPhone XR 安兔兔跑分出炉!竟与 iPhone XS 相差无几
- Laravel 5.8 :下载安装
- 【吴刚】PS软件基础实用技巧标准视频教程-吴刚-专题视频课程
- 人工智能发展飞速,未来几十年哪些职业会被逐渐取代,这些专业还值得选择吗?
- STM32F103时钟结构
- 提交azkaban任务时候报错:java.lang.RuntimeException: azkaban.jobExecutor.utils.process.ProcessFailureExceptio
- 中国的计算机网络技术学校,计算机系网络营销学校,计算机网络技术有哪些专科学校...