C# 爬虫:疫情实时信息图
生活随笔
收集整理的這篇文章主要介紹了
C# 爬虫:疫情实时信息图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
運行結果:
using System; using System.Drawing; using System.Text; using NSoup; using NSoup.Nodes; using System.IO; using System.Net; using System.Text.RegularExpressions; using System.Windows.Forms;namespace Pneumonia {public partial class MainForm : DevComponents.DotNetBar.OfficeForm{static string confirmedCount, suspectedCount, deadCount, curedCount, updateTime,dataUpdateTime;static string url = "https://3g.dxy.cn/newh5/view/pneumonia";static int count = 0;static Document doc;public MainForm() {this.EnableGlass = false;InitializeComponent();this.SizeChanged += new Resize(this).Form1_Resize; //窗口自適應代碼}private void MainForm_Load(object sender, EventArgs e) {timer1.Enabled = true;timer1.Interval = 1;timer1.Start();WebClient wc = new WebClient();byte[] htmlData = wc.DownloadData(url);string html = Encoding.UTF8.GetString(htmlData);logWrite(html);//將網頁內容寫入txt文件,以方便查看toolStripStatusLabel1.Text = DateTime.Now.ToString();}private void timer1_Tick(object sender, EventArgs e) {dataUpdateTime = DateTime.Now.ToString();count++;timer1.Interval = 300000;GetData();lbl1.Text = "? 病毒: " + regularMatchStr("getStatisticsService", "virus\":\"(.+?)\",");lbl2.Text = "? 傳染源: " + regularMatchStr("getStatisticsService", "infectSource\":\"(.+?)\",");lbl3.Text = "? 傳播途徑: " + regularMatchStr("getStatisticsService", "passWay\":\"(.+?)\",");lbl4.Text ="? "+regularMatchStr("getStatisticsService", "remark1\":\"(.+?)\",");lbl5.Text ="? "+regularMatchStr("getStatisticsService", "remark2\":\"(.+?)\",");Image map =UrlToImage("https://img1.dxycdn.com/2020/0201/450/3394153392393266839-135.png");pictureBox1.Image = map;Image chart = UrlToImage("https://img1.dxycdn.com/2020/0201/693/3394145745204021706-135.png");pictureBox2.Image = chart;updateTimeLbl.Text = "截至 " + updateTime + " 全國數據統計";confirmedLbl.Text = confirmedCount;suspectedLbl.Text = suspectedCount;deadLbl.Text = deadCount;curedLbl.Text = curedCount;}public static void GetData() {//直接通過url來獲取Document對象doc = NSoupClient.Connect(url).Get();//先獲取id為artContent的元素,再獲取所有的p標簽updateTime = ConvertStringToDateTime(regularMatchStr("getStatisticsService", "modifyTime\":(.+?),")).ToString();confirmedCount = regularMatchStr("getStatisticsService", "confirmedCount\":(.+?),");suspectedCount = regularMatchStr("getStatisticsService", "suspectedCount\":(.+?),");deadCount = regularMatchStr("getStatisticsService", "deadCount\":(.+?),");curedCount = regularMatchStr("getStatisticsService", "curedCount\":(.+?),");}#region 下載圖片到Imagepublic static Image UrlToImage(string url) {WebClient mywebclient = new WebClient();byte[] Bytes = mywebclient.DownloadData(url);using (MemoryStream ms = new MemoryStream(Bytes)){Image outputImg = Image.FromStream(ms);return outputImg;}}#endregionpublic static DateTime ConvertStringToDateTime(string timeStamp) {DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));long lTime = long.Parse(timeStamp + "0000");TimeSpan toNow = new TimeSpan(lTime);return dtStart.Add(toNow);}public static string regularMatchStr(string elementId, string regex) {Element p = doc.GetElementById(elementId);Regex reg = new Regex(regex, RegexOptions.IgnoreCase);//例如我想提取line中的NAME值Match match = reg.Match(p.Html());string value = match.Groups[1].Value;return value;}public static void logWrite(string Message) {if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\log.txt"))File.Create(AppDomain.CurrentDomain.BaseDirectory + "\\log.txt").Close();string fileName = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt";string content = DateTime.Now.ToLocalTime() + Message + "\r\n";StreamWriter sw = new StreamWriter(fileName, true);sw.Write(content);sw.Close(); sw.Dispose();}private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) {if (e.Button == MouseButtons.Left)//判斷鼠標的按鍵 {//點擊時判斷form是否顯示,顯示就隱藏,隱藏就顯示 if (this.WindowState == FormWindowState.Normal){this.WindowState = FormWindowState.Minimized;this.Hide();}else if (this.WindowState == FormWindowState.Minimized){this.Show();this.WindowState = FormWindowState.Normal;this.Activate();}}else if (e.Button == MouseButtons.Right){//右鍵退出事件 if (MessageBox.Show("是否需要關閉程序?", "提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)//出錯提示 {//關閉窗口 DialogResult = DialogResult.No;Dispose();Close();}}}private void timer2_Tick(object sender, EventArgs e) {toolStripStatusLabel1.Text = DateTime.Now.ToString() + " 刷新次數 : " + count + " 最新刷新時間 :" + dataUpdateTime;}private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {if (MessageBox.Show("是否確認退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK){// 關閉所有的線程this.Dispose();this.Close();}else{e.Cancel = true;}}private void MainForm_SizeChanged(object sender, EventArgs e) {//判斷是否選擇的是最小化按鈕if (WindowState == FormWindowState.Minimized){//隱藏任務欄區圖標this.ShowInTaskbar = false;//圖標顯示在托盤區notifyIcon1.Visible = true;}}private void 退出ToolStripMenuItem_Click(object sender, EventArgs e){if (MessageBox.Show("是否確認退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK){// 關閉所有的線程this.Dispose();this.Close();}}private void 顯示ToolStripMenuItem_Click(object sender, EventArgs e){WindowState = FormWindowState.Normal;}} }resize類
C# Winform控件自適應窗體大小:方法1(推薦)
需求:當窗體尺寸動態改變時,窗體中的各種控件(包括Panel以及Panel中的子控件)可以動態調節自身大小,以適應窗體內容比例。
方法:
第一步,新建一個類,代碼如下:
class Resize{private Form _form;public Resize(Form form){int count = form.Controls.Count * 2 + 2;float[] factor = new float[count];int i = 0;factor[i++] = form.Size.Width;factor[i++] = form.Size.Height;foreach (Control ctrl in form.Controls){factor[i++] = ctrl.Location.X / (float)form.Size.Width;factor[i++] = ctrl.Location.Y / (float)form.Size.Height;ctrl.Tag = ctrl.Size;}form.Tag = factor;this._form = form;}public void Form1_Resize(object sender, EventArgs e){float[] scale = (float[])this._form.Tag;int i = 2;foreach (Control ctrl in this._form.Controls) //panel的長寬增長到一個固定的值就不會再增長了,原因:Panel的寬和高上限是65535像素(https://blog.csdn.net/dufangfeilong/article/details/41805073?utm_source=blogxgwz5){ctrl.Left = (int)(this._form.Size.Width * scale[i++]);ctrl.Top = (int)(this._form.Size.Height * scale[i++]);ctrl.Width = (int)(this._form.Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width);ctrl.Height = (int)(this._form.Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height);}}}第二步,在Form的初始化函數中使用這個類:public Form_StockCount(){InitializeComponent();this.SizeChanged += new Resize(this).Form1_Resize; //窗口自適應代碼}C# Winform窗體和控件自適應大小:方法2
1.在項目中創建類AutoSizeForm
AutoSizeForm.cs文件代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CSharpFormApplication {class AutoResizeForm{//(1).聲明結構,只記錄窗體和其控件的初始位置和大小。public struct controlRect{public int Left;public int Top;public int Width;public int Height;}//(2).聲明 1個對象//注意這里不能使用控件列表記錄 List nCtrl;,因為控件的關聯性,記錄的始終是當前的大小。// public List oldCtrl= new List();//這里將西文的大于小于號都過濾掉了,只能改為中文的,使用中要改回西文public List<controlRect> oldCtrl = new List<controlRect>();int ctrlNo = 0;//1;//(3). 創建兩個函數//(3.1)記錄窗體和其控件的初始位置和大小,public void controllInitializeSize(Control mForm){controlRect cR;cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height;oldCtrl.Add(cR);//第一個為"窗體本身",只加入一次即可AddControl(mForm);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用//this.WindowState = (System.Windows.Forms.FormWindowState)(2);//記錄完控件的初始位置和大小后,再最大化//0 - Normalize , 1 - Minimize,2- Maximize}private void AddControl(Control ctl){foreach (Control c in ctl.Controls){ //**放在這里,是先記錄控件的子控件,后記錄控件本身//if (c.Controls.Count > 0)// AddControl(c);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用controlRect objCtrl;objCtrl.Left = c.Left; objCtrl.Top = c.Top; objCtrl.Width = c.Width; objCtrl.Height = c.Height;oldCtrl.Add(objCtrl);//**放在這里,是先記錄控件本身,后記錄控件的子控件if (c.Controls.Count > 0)AddControl(c);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用}}//(3.2)控件自適應大小,public void controlAutoSize(Control mForm){if (ctrlNo == 0){ //*如果在窗體的Form1_Load中,記錄控件原始的大小和位置,正常沒有問題,但要加入皮膚就會出現問題,因為有些控件如dataGridView的的子控件還沒有完成,個數少//*要在窗體的Form1_SizeChanged中,第一次改變大小時,記錄控件原始的大小和位置,這里所有控件的子控件都已經形成controlRect cR;// cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height;cR.Left = 0; cR.Top = 0; cR.Width = mForm.PreferredSize.Width; cR.Height = mForm.PreferredSize.Height;oldCtrl.Add(cR);//第一個為"窗體本身",只加入一次即可AddControl(mForm);//窗體內其余控件可能嵌套其它控件(比如panel),故單獨抽出以便遞歸調用}float wScale = (float)mForm.Width / (float)oldCtrl[0].Width;//新舊窗體之間的比例,與最早的舊窗體float hScale = (float)mForm.Height / (float)oldCtrl[0].Height;//.Height;ctrlNo = 1;//進入=1,第0個為窗體本身,窗體內的控件,從序號1開始AutoScaleControl(mForm, wScale, hScale);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用}private void AutoScaleControl(Control ctl, float wScale, float hScale){int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;//int ctrlNo = 1;//第1個是窗體自身的 Left,Top,Width,Height,所以窗體控件從ctrlNo=1開始foreach (Control c in ctl.Controls){ //**放在這里,是先縮放控件的子控件,后縮放控件本身//if (c.Controls.Count > 0)// AutoScaleControl(c, wScale, hScale);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用ctrLeft0 = oldCtrl[ctrlNo].Left;ctrTop0 = oldCtrl[ctrlNo].Top;ctrWidth0 = oldCtrl[ctrlNo].Width;ctrHeight0 = oldCtrl[ctrlNo].Height;//c.Left = (int)((ctrLeft0 - wLeft0) * wScale) + wLeft1;//新舊控件之間的線性比例//c.Top = (int)((ctrTop0 - wTop0) * h) + wTop1;c.Left = (int)((ctrLeft0) * wScale);//新舊控件之間的線性比例。控件位置只相對于窗體,所以不能加 + wLeft1c.Top = (int)((ctrTop0) * hScale);//c.Width = (int)(ctrWidth0 * wScale);//只與最初的大小相關,所以不能與現在的寬度相乘 (int)(c.Width * w);c.Height = (int)(ctrHeight0 * hScale);//ctrlNo++;//累加序號//**放在這里,是先縮放控件本身,后縮放控件的子控件if (c.Controls.Count > 0)AutoScaleControl(c, wScale, hScale);//窗體內其余控件還可能嵌套控件(比如panel),要單獨抽出,因為要遞歸調用if (ctl is DataGridView){DataGridView dgv = ctl as DataGridView;Cursor.Current = Cursors.WaitCursor;int widths = 0;for (int i = 0; i < dgv.Columns.Count; i++){dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells); // 自動調整列寬 widths += dgv.Columns[i].Width; // 計算調整列后單元列的寬度和 }if (widths >= ctl.Size.Width) // 如果調整列的寬度大于設定列寬 dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; // 調整列的模式 自動 elsedgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; // 如果小于 則填充 Cursor.Current = Cursors.Default;}}}}}2.在要自適應大小的Form中自定義全局類對象AutoResizeForm asc = new AutoResizeForm();3.在要自適應大小的Form的load事件和SizeChange事件中執行對象方法private void WidgetAutoResizeForm_Load(object sender, EventArgs e){asc.controllInitializeSize(this);}private void WidgetAutoResizeForm_SizeChanged(object sender, EventArgs e){asc.controlAutoSize(this);}From窗體代碼:using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;namespace CSharpFormApplication {public partial class WidgetAutoResizeForm : Form{AutoResizeForm asc = new AutoResizeForm();public WidgetAutoResizeForm(){InitializeComponent();}private void WidgetAutoResizeForm_Load(object sender, EventArgs e){asc.controllInitializeSize(this);}private void WidgetAutoResizeForm_SizeChanged(object sender, EventArgs e){asc.controlAutoSize(this);}} }總結
以上是生活随笔為你收集整理的C# 爬虫:疫情实时信息图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WPF Datagrid合并表头的思路
- 下一篇: C# 外接(网口)双摄像头视频获取