/// <summary> /// 进度条增加1 /// </summary> void AddRow(Baiduxinxi xx) { //解决 线程间操作无效: 从不是创建控件“dgv1”的线程访问它。 的问题 //使用委托执行添加一行数据 Action action = new Action(() => { int index = this.dgv1.Rows.Add(); this.dgv1.Rows[index].Cells[0].Value = xx.Name; this.dgv1.Rows[index].Cells[1].Value = xx.Url; this.dgv1.Rows[index].Cells[2].Value = xx.Upload; this.dgv1.Rows[index].Cells[3].Value = xx.Size; }); //在控件线程中执行代码,添加行 Invoke(action); }
/// <summary> /// 查询下一页 /// </summary> private void SearchNextPage() { if (!string.IsNullOrEmpty(key)) { lock (locker) { try { if (GetXml()) { SetMessage("开始加载数据"); SetProgressBar(30); HtmlWeb html = new HtmlWeb(); // HtmlAgilityPack 设置 请求超时 SetTimeout(html); HtmlAgilityPack.HtmlDocument doc = html.Load(webUrl); HtmlNodeCollection htmlnodecol = doc.DocumentNode.SelectNodes(xpathNodes); SetMessage("数据加载成功,正在显示"); if (htmlnodecol == null) { SetMessage("没有采集到数据"); } else { foreach (var hn in htmlnodecol) { try { //如果没有标题和链接则跳出 if (hn.SelectSingleNode(xpathName) == null || hn.SelectSingleNode(xpathUrl) == null) { continue; } Baiduxinxi baidu = new Baiduxinxi(); string url = hn.SelectSingleNode(xpathUrl) != null?hn.SelectSingleNode(xpathUrl).Attributes["href"].Value : ""; string name = hn.SelectSingleNode(xpathName) != null?hn.SelectSingleNode(xpathName).InnerText : ""; string size = hn.SelectSingleNode(xpathSize) != null?hn.SelectSingleNode(xpathSize).InnerText : ""; string upload = hn.SelectSingleNode(xpathUpload) != null?hn.SelectSingleNode(xpathUpload).InnerText : ""; //如果链接没有主机地址,则添加 if (url.IndexOf("http") == -1) { Uri uri = new Uri(webUrl); url = uri.Scheme + "://" + uri.Host + url; } upload = upload.Replace("上传", "").Replace("时间", "").Replace("大小", "").Replace("发布", "").Replace(":", "").Replace(":", ""); size = size.Replace("上传", "").Replace("时间", "").Replace("大小", "").Replace("发布", "").Replace(":", "").Replace(":", ""); url = (!string.IsNullOrEmpty(url)) ? url.Trim().Replace(" ", "").Replace(" ", "") : url; name = (!string.IsNullOrEmpty(name)) ? name.Trim() : name; size = (!string.IsNullOrEmpty(size)) ? size.Trim().Replace(" ", "").Replace(" ", "") : size; upload = (!string.IsNullOrEmpty(upload)) ? upload.Trim().Replace(" ", "").Replace(" ", "") : upload; baidu.Url = url; baidu.Name = name; baidu.Size = size; baidu.Upload = upload; AddRow(baidu); AddProgressBar(); } catch (Exception ex) { ex.ToString().ToShow(); } } pageNum++;//页面增加 AddProgressBarAll(); SetMessage("数据加载完成"); } } } catch (Exception ex) { ex.ToShow(); } } } }