private new void Show() { base.Show(); // https://stackoverflow.com/questions/1277691/how-to-retrieve-the-scrollbar-position-of-the-webbrowser-control-in-net System.Windows.Forms.HtmlDocument htmlDoc = webBrowser1.Document; if (htmlDoc != null) { vPos = htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop; hPos = htmlDoc.GetElementsByTagName("HTML")[0].ScrollLeft; } ShowText(richTextBox1.Text, webBrowser1); }
public static void AttachValueToDataSource(DataSet ds, HtmlDocument doc) { LoggingService.DebugFormatted("绑定HTML表单数据:{0} 到数据源...", new object[] { doc.Url }); foreach (string str in tags) { HtmlElementCollection elementsByTagName = doc.GetElementsByTagName(str); foreach (HtmlElement element in elementsByTagName) { DataRow row; string attribute = element.GetAttribute("dbtable"); string str3 = element.GetAttribute("dbcolumn"); if (GetDataRow(ds, attribute, out row) && (row != null)) { if (row.RowState == DataRowState.Unchanged) { row.SetModified(); } if (!(string.IsNullOrEmpty(str3) || !row.Table.Columns.Contains(str3))) { string str4 = element.GetAttribute("value").Trim(); row[str3] = (str4 == string.Empty) ? Convert.DBNull : str4; LoggingService.DebugFormatted("设置表:{0}列:{1}的值为:{2}", new object[] { attribute, str3, str4 }); } } } } }
private void WebBrowserDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { try { WebBrowser webBrowser = ((WebBrowser)sender); System.Windows.Forms.HtmlDocument html = webBrowser.Document; string sTitle = html.Title; foreach (HtmlElement select in html.GetElementsByTagName("select")) { if (select.Name.Equals("anho")) { select.Focus(); select.SetAttribute("value", año); select.InvokeMember("onchange"); select.RemoveFocus(); } if (select.Name.Equals("mes")) { select.Focus(); select.SetAttribute("value", mes); select.InvokeMember("onchange"); select.RemoveFocus(); } } foreach (HtmlElement button in html.GetElementsByTagName("input")) { if (button.Name.Equals("B1")) { cadhtml = webBrowser.DocumentText; if (consulta == true) { rpta = true; return; } button.RaiseEvent("onclick"); consulta = true; } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Tipo de Cambio", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void setScrollBar(int page) { System.Windows.Forms.HtmlDocument htmlDoc = webBrowser1.Document; if (page > 0) { htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop = Convert.ToInt32(page); } }
private string FindTitle(HtmlDocument doc) { var result = String.Empty; IQueryable<HtmlElement> h1HEC = doc.GetElementsByTagName("h1").AsQueryable().Cast<HtmlElement>(); var titleElement = h1HEC.First(e => e.GetAttribute("class") == "title"); return result; }
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { System.Windows.Forms.HtmlDocument htmlDoc = webBrowser1.Document; try { htmlDoc = webBrowser1.Document; if (htmlDoc != null) { htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop = vPos; htmlDoc.GetElementsByTagName("HTML")[0].ScrollLeft = hPos; } } catch (Exception ex) { vPos = 0; hPos = 0; } }
/// <summary> /// Display an HTML document in the tree view, organizing the tree /// in accordance with the Document Object Model (DOM) /// </summary> /// <param name="docResponse">the document to display</param> /// <remarks><para>Called by the thread.start to set up for filling the DOM tree</para> /// Has to be passed as an object for the ParameterizedThreadStart</remarks> public void DisplayInTree(HtmlDocument docResponse) { HtmlElementCollection elemColl = docResponse.GetElementsByTagName("html"); _treeView.Nodes.Clear(); var rootNode = new TreeNode("Web response") {Tag = -1}; _treeView.Nodes.Add(rootNode); FillDomTree(elemColl, rootNode, 0); }
private void Login(string username, string password) { doc = webBrowser1.Document; doc.All["ctl00_ctl17_Username"].SetAttribute("value", username); doc.All["ctl00_ctl17_Password"].SetAttribute("value", password); HtmlElementCollection oHtmlElements = doc.GetElementsByTagName("input"); oHtmlElements["ctl00_ctl17_LoginButton"].InvokeMember("click"); }
private Dictionary<String, String> GetPostData(HtmlDocument doc,string formName, Uri target, Uri baseURL) { Dictionary<String, String> ret = new Dictionary<String, String>(); foreach (HtmlElement form in doc.GetElementsByTagName("save_passenger_single")) if ((form.GetAttribute("mode").ToLower() == "post") && ((target == (new Uri(baseURL, form.GetAttribute("target")))))) foreach (HtmlElement widget in form.GetElementsByTagName("input")) { String name = widget.GetAttribute("name"); if (name != "") ret.Add(name, widget.GetAttribute("value")); } return ret; }
private HtmlElement getHTMLElemStr(String sElem, System.Windows.Forms.HtmlDocument doc) { var cName = doc.GetElementsByTagName("div"); HtmlElement elem = null; foreach (HtmlElement element in cName) { if (element.GetAttribute("className") == sElem) { elem = element; break; } } return(elem); }
public void setPageNumber() { if (webBrowser1.Url.AbsoluteUri == createURL()) { System.Windows.Forms.HtmlDocument htmlDoc = webBrowser1.Document; int scrollTop = htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop; string mySQL = string.Empty; mySQL += "UPDATE BookTable SET page_num = ('" + scrollTop + "') "; mySQL += "WHERE user_id = ('" + user_id + "') and book_id = ('" + book_id + "') ;"; sqliteDatabase.execSqlite(mySQL); } }
/// <summary> /// 表示されている自分のツイート数をカウントする /// 非常に遅いので未使用 /// </summary> /// <param name="doc"></param> /// <returns></returns> public int getTweetCount(HtmlDocument doc) { int count = 0; string href0 = ""; foreach (HtmlElement el in doc.GetElementsByTagName("a")) { string cname = el.GetAttribute("className"); if (cname == "tweet-timestamp js-permalink") { string href = el.GetAttribute("href"); if ( href0 != href && href.StartsWith("http://twitter.com/#!/" + screenName)== true) { count++; href0 = href; } } } return count; }
private void button1_Click(object sender, EventArgs e) { //Авторизация webBrowser1.Show(); webBrowser1.ScriptErrorsSuppressed = true; webBrowser1.Navigate("https://secure.twitch.tv/signup"); while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } System.Windows.Forms.HtmlDocument doc = webBrowser1.Document; HtmlElementCollection cjlection = doc.GetElementsByTagName("input"); foreach (HtmlElement f in cjlection) { if (f.Name == "login") { f.InnerText = textBox1.Text; } } foreach (HtmlElement f in cjlection) { if (f.Name == "password") { f.InvokeMember("click"); f.InnerText = "password"; f.InvokeMember("click"); } } foreach (HtmlElement f in cjlection) { if (f.Name == "email") { f.InnerText = textBox1.Text + "@mektown.ru"; } } screanShot(); textBox2.Text = webBrowser1.DocumentText; }
/// <summary> /// 功能描述:得到数据 /// 作 者:huangsp /// 创建日期:2016-08-23 17:11:55 /// 任务编号:信息收集子系统开发 /// </summary> /// <param name="m_browser1">m_browser1</param> /// <param name="strurl">strurl</param> /// <returns>返回值</returns> private bool GetInfo(WebBrowser m_browser1, string strurl, string strkeyword) { try { NavateAgain: m_intcount = 0; m_browser1.Navigate(strurl); while (m_browser1.ReadyState != WebBrowserReadyState.Complete) { Delay(3); } if (m_browser1.Document != null && m_browser1.Document.Body != null) { //为确认本次访问为正常用户行为,请您协助验证。 if (Regex.IsMatch(m_browser1.Document.Body.InnerText, "为确认本次访问为正常用户行为,请您协助验证")) { VerifyCode(); goto NavateAgain; } if (m_browser1.Document.Body.InnerText.Contains("没有找到相关结果")) { return(false); } } int m_intPageSum = 0; LinkedList <T_Web_TianYanCha_POI> Listty = new LinkedList <T_Web_TianYanCha_POI>(); System.Windows.Forms.HtmlDocument doc = m_browser1.Document; if (doc != null) { HtmlElementCollection elems = doc.GetElementsByTagName("div"); if (elems.Count == 8) { Delay(5); } foreach (HtmlElement el in elems) { if (el.GetAttribute("className").Equals("total ng-binding")) { string str = el.InnerText; m_intPageSum = int.Parse(Regex.Match(str, "\\d+").Value); break; } } if (m_intPageSum < 1) { goto NavateAgain; } for (int i = 1; i < m_intPageSum + 1; i++) { Dictionary <string, string> dic = new Dictionary <string, string>(); GetUrlList(elems, ref dic); if (dic.Count != 0) { GetInner(dic); m_browser2.Dispose(); m_browser2 = null; } if (TaskProcessor.Complete) { break; } IntPtr pHandle = GetCurrentProcess(); SetProcessWorkingSetSize(pHandle, -1, -1); string strurls = string.Format(strUrl, strkeyword, i + 1); m_browser1.Navigate(strurls); while (m_browser1.ReadyState != WebBrowserReadyState.Complete) { Delay(3); } doc = m_browser1.Document; if (doc != null) { elems = doc.GetElementsByTagName("div"); if (elems != null) { Application.DoEvents(); if (elems.Count == 26 || elems.Count == 27) { m_browser1.Navigate(strurls); Delay(3); } } } } } else { goto NavateAgain; } return(true); //1、快速获取天眼查网站数据,尽可能确保全面; //2、获取信息要包含 名称、地址、电话、网址、注册时间、核准时间、状态(开业、注销)、组织机构代码、工商注册号、统一信用代码、登记机关。 } catch (Exception exc) { MessageBox.Show(exc.ToString() + (exc.InnerException != null ? exc.InnerException.ToString() : ""), "错误"); return(false); } finally { } }
private void Start() { try { start: m_blnLoaded = false; m_browser1.BeginInvoke(new MethodInvoker(delegate() { m_browser1.Navigate(m_strListUrl); })); int intSleepIndex = 0; while (!m_blnLoaded) { Thread.Sleep(100); intSleepIndex++; if (intSleepIndex >= 100) { break; //goto start; } } Thread.Sleep(1000); try { //验证码判断 System.Windows.Forms.HtmlDocument doc = null; m_browser1.BeginInvoke(new MethodInvoker(delegate() { doc = m_browser1.Document; })); while (doc == null) { Thread.Sleep(10); } if (doc != null && doc.Body != null) { //为确认本次访问为正常用户行为,请您协助验证。 if (Regex.IsMatch(doc.Body.InnerText, "为确认本次访问为正常用户行为,请您协助验证")) { VerifyCode(); goto start; } if (doc.Body.InnerText.Contains("没有找到相关结果")) { SendMsgToMainClientEx("-1"); Thread.Sleep(1000); return; } } if (m_blnGetCount) { if (doc != null) { // int intOut = 0; //goHere: // intOut++; string strReg = @"共(\d+)页"; Match match = Regex.Match(doc.Body.InnerText, strReg); if (match != null) { string strNum = Regex.Match(match.Value, @"\d+").Value; int intCount = int.Parse(strNum); SendMsgToMainClientEx("count:" + intCount); } else { Thread.Sleep(1000); //if (intOut > 30) //{ goto start; //} //goto goHere; } } } if (doc != null) { #region HtmlElementCollection elems = doc.GetElementsByTagName("div"); Dictionary <string, string> dic = new Dictionary <string, string>(); try { GetUrlList(elems, ref dic); } catch { goto start; } if (dic.Count != 0) { GetInner(dic); } else { goto start; } #endregion } else { goto start; } } catch { goto start; } } catch { } finally { Application.Exit(); Process.GetCurrentProcess().Kill(); } }
public void GetInner(Dictionary <string, string> dic) { #region 详情页 foreach (var item in dic) { Contect: try { m_blnDefLoaded = false; m_browser2.Navigate(item.Key); int intSleepIndex = 0; while (!m_blnDefLoaded) { Thread.Sleep(100); intSleepIndex++; if (intSleepIndex > 100) { goto Contect; } } System.Windows.Forms.HtmlDocument docIn = null; m_browser2.BeginInvoke(new MethodInvoker(delegate() { docIn = m_browser2.Document; })); while (docIn == null) { Thread.Sleep(10); } if (docIn != null && docIn.Body != null) { string str = docIn.Body.InnerText; //为确认本次访问为正常用户行为,请您协助验证。 if (Regex.IsMatch(str, "为确认本次访问为正常用户行为,请您协助验证")) { VerifyCode(); goto Contect; } HtmlElementCollection elemsIn = docIn.GetElementsByTagName("div"); if (elemsIn.Count == 8) { goto Contect; } if (elemsIn != null) { string strtyTel = string.Empty; string strtyUrl = string.Empty; string strtyEmail = string.Empty; string strName = string.Empty; foreach (HtmlElement elIn in elemsIn) { if (elIn.GetAttribute("className").Equals("company_info_text")) { string strMsg = elIn.InnerText; strMsg = Regex.Replace(strMsg, @"暂无|\s", ""); int int1 = strMsg.IndexOf("电话:"); int int2 = strMsg.IndexOf("地址:"); strMsg = strMsg.Substring(int1, int2 - int1); string[] values = Regex.Split(strMsg, @"电话:|邮箱:|网址:"); if (values.Length == 4) { strtyTel = values[1]; strtyEmail = values[2]; strtyUrl = values[3]; } strtyTel = string.IsNullOrEmpty(strtyTel) ? "暂无" : strtyTel; strtyEmail = string.IsNullOrEmpty(strtyEmail) ? "暂无" : strtyEmail; strtyUrl = string.IsNullOrEmpty(strtyUrl) ? "暂无" : strtyUrl; //if (elIn.Children.Count == 10) //{ // strtyTel = elIn.Children[2].InnerText.Trim().Replace("电话: ", ""); // strtyEmail = elIn.Children[3].InnerText.Trim().Replace("邮箱: ", ""); // strtyUrl = elIn.Children[5].InnerText.Trim().Replace("网址: ", ""); //} //else if (elIn.Children.Count == 11) //{ // strtyTel = elIn.Children[3].InnerText.Trim().Replace("电话: ", ""); // strtyEmail = elIn.Children[3].InnerText.Trim().Replace("邮箱: ", ""); // strtyUrl = elIn.Children[6].InnerText.Trim().Replace("网址: ", ""); //} } else if (elIn.GetAttribute("className").Equals("row b-c-white company-content")) { HtmlElementCollection els = elIn.Children[0].Children[0].Children; if (els.Count > 1) { strName = els[1].Children[0].Children[0].Children[0].InnerText; } break; } else { continue; } } T_Web_TianYanCha_POI ty = new T_Web_TianYanCha_POI(); ty.LegalPersonName = strName; ty.Tel = strtyTel; ty.Email = strtyEmail; ty.Name = item.Value; DataTable dt = GetDataTable(new List <T_Web_TianYanCha_POI>() { ty }); ExcelEX.DataTableToExcel(m_savepath, dt, true); SendMsgToMainClientEx("+"); } } } catch { goto Contect; } } #endregion }
private bool SignETao(HtmlDocument doc) { HtmlElement eleBtn = null; foreach (HtmlElement ele in doc.GetElementsByTagName("div")) { if (ele.InnerText != null && ele.GetAttribute("classname").Equals("ci_receive") && ele.InnerText.Equals("签到") ) { eleBtn = ele; break; } } if (eleBtn != null) { eleBtn.InvokeMember("click"); return true; } return false; }
/// <summary> /// 將網頁原始碼擷取出來 /// </summary> /// <param name="HD">轉換網頁的物件</param> /// <returns>回傳出網頁的原始碼</returns> public string Getwebpagesource(HtmlDocument HD) { JQ(HD); HtmlElement htmlElement = HD.GetElementsByTagName("HTML")[0]; return htmlElement.InnerHtml; }
/********************************************************** * * 포탈 * **********************************************************/ private void mainBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { /********************************************************** * * PMS 막힘 확인 확인 * **********************************************************/ if (e.Url.ToString().IndexOf("http://10.99.1.4/IIWeb/default.htm") != -1 && pmsError == false) { pmsError = true; MessageBox.Show("PMS를 설치 혹은 우회 하셔야 합니다 :(", "Robot의 경고"); System.Diagnostics.Process.Start("http://10.99.1.4/IIWeb/default.htm"); System.Diagnostics.Process[] mProcess = System.Diagnostics.Process.GetProcessesByName(Application.ProductName); foreach (System.Diagnostics.Process p in mProcess) p.Kill(); Application.Exit(); } /********************************************************** * * 최신 버전 확인 * **********************************************************/ if (e.Url.ToString().IndexOf("carpedm20.net76.net/robot_version.html") != -1) { doc = mainBrowser.Document as HtmlDocument; /************************************ * 최신 버전 확인중 ************************************/ loadingLabel.Text = "최신 버전 확인중"; loadingProgressBar.Value += 2; if (doc.GetElementById("version") == null) { loadingLabel.Text = "최신 버전 확인 실패 :("; mainBrowser.Navigate("https://portal.unist.ac.kr/EP/web/login/unist_acube_login_int.jsp"); } lastestVersion = doc.GetElementById("version").InnerText.Trim(); /************************************ * 작동하지 않는 서비스 있을시 ************************************/ if (doc.GetElementById("urlError").InnerText.Trim() == "true") { urlError = true; bbStartUrl = doc.GetElementById("bbStartUrl").InnerText.Trim(); bbEndUrl = doc.GetElementById("bbEndUrl").InnerText.Trim(); bbAnnounceUrl = doc.GetElementById("bbAnnounceUrl").InnerText.Trim(); libraryStartUrl = doc.GetElementById("libraryStartUrl").InnerText.Trim(); libraryEndUrl = doc.GetElementById("libraryEndUrl").InnerText.Trim(); dormStartUrl = doc.GetElementById("dormStartUrl").InnerText.Trim(); dormEndUrl = doc.GetElementById("dormEndUrl").InnerText.Trim(); mailStartUrl = doc.GetElementById("mailStartUrl").InnerText.Trim(); mailEndUrl = doc.GetElementById("mailEndUrl").InnerText.Trim(); } /************************************ * 공지사항 ************************************/ if (doc.GetElementById("announce").InnerText != null) { MessageBox.Show(doc.GetElementById("announce").InnerText, doc.GetElementById("announceTitle").InnerText); } if (currentVersion.IndexOf(lastestVersion) != -1) { loadingLabel.Text = "최신 버전입니다 :)"; } else { loadingLabel.Text = "최신 버전이 아닙니다 :("; } mainBrowser.Navigate("https://portal.unist.ac.kr/EP/web/login/unist_acube_login_int.jsp"); } /********************************************************** * * 로그인 창에서 변수 입력 * **********************************************************/ loadingProgressBar.Value += 1; if (e.Url.ToString() == "https://portal.unist.ac.kr/EP/web/login/unist_acube_login_int.jsp") { System.Threading.Thread.Sleep(2000); doc = mainBrowser.Document as HtmlDocument; doc.GetElementById("id").SetAttribute("value", Program.id); doc.GetElementsByTagName("input")["UserPassWord"].SetAttribute("value", Program.password); doc.InvokeScript("doLogin"); /************************************ * 포탈 로그인 단계 ************************************/ loadingLabel.Text = "포탈 로그인중"; loadingProgressBar.Value += 5; } /********************************************************** * * 첫 로그인, 이름 저장, 학사 공지로 이동 * **********************************************************/ if (e.Url.ToString() == "http://portal.unist.ac.kr/EP/web/portal/jsp/EP_TopFixed.jsp") { if (isPortalComplete == false) { /************************************ * 포탈 로그인 완료 ************************************/ loadingLabel.Text = "포탈 로그인 완료"; loadingProgressBar.Value += 5; portalCookie = mainBrowser.Document.Cookie; welcomeLabel.Click += new EventHandler(welcomeLabel_Click); userName = mainBrowser.DocumentTitle.ToString().Split('-')[1].Split('/')[0]; welcomeLabel.Text = userName + " 님 환영합니다 :^)"; portal = new Portal(portalCookie, this); showBoardGrid(1); isPortalComplete = true; browser.Navigate(bbStartUrl); } else { browser.Navigate(bbStartUrl); } } }
private HtmlElement GetElementByXpath(HtmlDocument doc, string xpath) { if (doc == null) return null; xpath = xpath.Replace("/html/", ""); HtmlElementCollection eleColec = doc.GetElementsByTagName("html"); if (eleColec.Count == 0) return null; HtmlElement ele = eleColec[0]; string[] tagList = xpath.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); foreach (string tag in tagList) { System.Text.RegularExpressions.Match mat = System.Text.RegularExpressions.Regex.Match(tag, "(?<tag>.+)\\[@id='(?<id>.+)'\\]"); if (mat.Success == true) { string id = mat.Groups["id"].Value; HtmlElement tmpEle = doc.GetElementById(id); if (tmpEle != null) ele = tmpEle; else { ele = null; break; } } else { mat = System.Text.RegularExpressions.Regex.Match(tag, "(?<tag>.+)\\[(?<ind>[0-9]+)\\]"); if (mat.Success == false) { HtmlElement tmpEle = null; foreach (HtmlElement it in ele.Children) { if (it.TagName.ToLower() == tag) { tmpEle = it; break; } } if (tmpEle != null) ele = tmpEle; else { ele = null; break; } } else { string tagName = mat.Groups["tag"].Value; int ind = int.Parse(mat.Groups["ind"].Value); int count = 0; HtmlElement tmpEle = null; foreach (HtmlElement it in ele.Children) { if (it.TagName.ToLower() == tagName) { count++; if (ind == count) { tmpEle = it; break; } } } if (tmpEle != null) ele = tmpEle; else { ele = null; break; } } } } if (ele != null) { if (scrollToViewToolStripMenuItem.Enabled == true) { ele.ScrollIntoView(true); } else { ele.ScrollIntoView(false); } if (colorElementToolStripMenuItem.Enabled == true) { CheckElement(ele); } //ele.Focus(); } return ele; }
private bool ClickNextTab(HtmlDocument doc) { string currentTab = string.Empty; foreach (HtmlElement ele in doc.GetElementsByTagName("li")) { if (ele.GetAttribute("classname").Contains("ui-tab-trigger-item ui-tab-trigger-item-current")) { currentTab = ele.Children[0].InnerText; break; } } string nextTab = string.Empty; if (currentTab.Equals("收益")) { nextTab = "转入"; } else if (currentTab.Equals("转入")) { nextTab = "转出"; } else if (currentTab.Equals("转出")) { return false; } else { return false; } foreach (HtmlElement ele in doc.GetElementsByTagName("a")) { if (ele.InnerText != null && ele.GetAttribute("classname").Equals("ui-tab-trigger-text ui-bill-tab-text") && ele.InnerText.Equals(nextTab)) { ele.InvokeMember("click"); return true; } } return false; }
protected bool GetTableColumnValueFromHtmlDocument(HtmlDocument doc, string dbtable, string dbcolumn, ref object result) { foreach (string str in WebBrowserExtensions.tags) { HtmlElementCollection elementsByTagName = doc.GetElementsByTagName(str); foreach (HtmlElement element in elementsByTagName) { string attribute = element.GetAttribute("dbtable"); string str3 = element.GetAttribute("dbcolumn"); if (((!string.IsNullOrEmpty(attribute) && !string.IsNullOrEmpty(dbcolumn)) && (attribute == dbtable)) && (str3 == dbcolumn)) { result = element.GetAttribute("value"); return true; } } } return false; }
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath) { return; } if (menuItems[0].Text.Equals("Stop")) { if (webBrowser1.Url.ToString() == "https://impweb.cuny.edu/oam/Portal_Login1.html") { System.Windows.Forms.HtmlDocument source = webBrowser1.Document; HtmlElement head = source.GetElementsByTagName("head")[0]; HtmlElement s = source.CreateElement("script"); s.SetAttribute("text", "document.getElementById('login').value = '" + textBox1.Text + "'; void(0);"); head.AppendChild(s); s.SetAttribute("text", "document.getElementById('password').value = '" + textBox2.Text + "'; void(0);"); head.AppendChild(s); s.SetAttribute("text", "document.getElementsByName(\"submit\")[0].click();"); head.AppendChild(s); } else if (webBrowser1.Url.ToString().Contains("https://impweb.cuny.edu/oam/InvalidLogin.html")) { trayIcon.ShowBalloonTip(1000, "Class Notifier", "Invalid login. Please check your username/password.", ToolTipIcon.Error); timer1.Enabled = false; menuItems[0].Text = "Start"; menuItems[1].Enabled = true; } else if (webBrowser1.Url.ToString() == "https://impweb.cuny.edu/xlWebApp/") { trayIcon.ShowBalloonTip(1000, "Class Notifier", "Successfully logged in. Will now run in the background and check for classes every " + textBox3.Text + " seconds.", ToolTipIcon.Info); webBrowser1.Navigate("https://hrsa.cunyfirst.cuny.edu/psc/cnyhcprd/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_CART.GBL?"); } else if (webBrowser1.Url.ToString() == "https://hrsa.cunyfirst.cuny.edu/psc/cnyhcprd/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_CART.GBL?&") { HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); string source = webBrowser1.DocumentText; htmlDoc.LoadHtml(source); var pageTitle = htmlDoc.GetElementbyId("DERIVED_REGFRM1_SS_TRANSACT_TITLE"); if (pageTitle != null) { if (pageTitle.InnerText == "Add Classes") { checkClasses(); timer1.Enabled = true; } } else { System.Windows.Forms.HtmlDocument source1 = webBrowser1.Document; HtmlElement head = source1.GetElementsByTagName("head")[0]; HtmlElement s = source1.CreateElement("script"); s.SetAttribute("text", "var buttons = document.getElementsByName(\"SSR_DUMMY_RECV1$sels$0\"); buttons[1].checked = true; void(0);"); head.AppendChild(s); s.SetAttribute("text", "submitAction_win0(document.win0, 'DERIVED_SSS_SCT_SSR_PB_GO');"); head.AppendChild(s); } } //confirm classes if (webBrowser1.Url.ToString().Contains("https://hrsa.cunyfirst.cuny.edu/psc/cnyhcprd/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_ADD.GBL?Page=SSR_SSENRL_ADD_C")) { webBrowser1.Navigate("javascript: document.getElementsByName(\"DERIVED_REGFRM1_SSR_PB_SUBMIT\")[0].click();"); } //finished enrolling if (webBrowser1.Url.ToString() == "https://hrsa.cunyfirst.cuny.edu/psc/cnyhcprd/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_ADD.GBL") { trayIcon.ShowBalloonTip(1000, "Class Notifier", "Finished enrolling. Will continue checking for other classes to open.", ToolTipIcon.Info); } } }
private bool GetMaoquan(HtmlDocument doc) { foreach (HtmlElement ele in doc.GetElementsByTagName("div")) { if (ele.InnerText != null) { if (ele.GetAttribute("classname").Equals("tc_kapindao cgShow") && !string.IsNullOrEmpty(ele.Style) && ele.Style.ToLower().Equals("display: block")) { return true; } if (ele.InnerText.Equals("天天签到领猫券")) { ele.InvokeMember("click"); } } } return false; }
public static void Hj(HtmlDocument doc, string category) { double num = 0.0; foreach (string str in tags) { HtmlElementCollection elementsByTagName = doc.GetElementsByTagName(str); foreach (HtmlElement element in elementsByTagName) { string id = element.Id; string attribute = element.GetAttribute("sfcategory"); if ((element.GetAttribute("type") != "hidden") && !string.IsNullOrEmpty(attribute)) { foreach (string str4 in attribute.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { double num2; if ((str4 == category) && double.TryParse(element.GetAttribute("value"), out num2)) { num += num2; } } } } } try { SetHtmlElementValue(doc.GetElementById(category), num.ToString("0.00")); } catch { } }
public static void GetData(HtmlDocument doc, DataSet ds, Dictionary<string, InvokeResult> invokes) { if ((doc == null) || (ds == null)) { throw new ArgumentNullException("doc or ds"); } List<HtmlElement> list = new List<HtmlElement>(); foreach (string str in tags) { HtmlElementCollection elementsByTagName = doc.GetElementsByTagName(str); foreach (HtmlElement element in elementsByTagName) { string attribute = element.GetAttribute("ref"); if ((attribute != null) && (attribute.Trim().Length > 0)) { list.Add(element); } else { SetHtmlElementValue(doc, ds, element, invokes); } } } if (LoggingService.IsDebugEnabled) { LoggingService.Debug("获取具有REF属性的数据..."); } foreach (HtmlElement element in list) { SetHtmlElementValue(doc, ds, element, invokes); } }
private bool RetrieveDaily(HtmlDocument doc, MoneyDatabaseUpdater dbUpdater) { bool isRetrievedAny = false; foreach (HtmlElement eleTr in doc.GetElementsByTagName("tr")) { DateTime billTime = DateTime.Now; double amount = 0; byte changeType = 0; foreach(HtmlElement eleTd in eleTr.Children) { string className = eleTd.GetAttribute("classname"); if (className.Contains("billTime")) { try { billTime = DateTime.Parse(eleTd.InnerText); } catch { continue; } } else if (className.Contains("ft-bold")) { amount = this.GetAmountFromText(eleTd.InnerText); } else if (className.Contains("billAmount")) { changeType = this.GetTypeFromText(eleTd.InnerText); } } if (amount != 0) { Debug.Assert(changeType != 0, "未知的类型出现了!"); dbUpdater.AddDaily(billTime, amount, changeType); isRetrievedAny = true; } } return isRetrievedAny; }
public void GetInner(Dictionary <string, string> dic) { #region 详情页 m_browser2 = new WebBrowser(); foreach (var item in dic) { Contect: m_browser2.Navigate(item.Key); Delay(2); System.Windows.Forms.HtmlDocument docIn = m_browser2.Document; if (docIn != null && docIn.Body != null) { string str = docIn.Body.InnerText; //为确认本次访问为正常用户行为,请您协助验证。 if (Regex.IsMatch(str, "为确认本次访问为正常用户行为,请您协助验证")) { VerifyCode(); goto Contect; } HtmlElementCollection elemsIn = docIn.GetElementsByTagName("div"); if (elemsIn.Count == 8) { goto Contect; } if (elemsIn != null) { string strtyTel = null; string strtyUrl = null; string strtyEmail = null; foreach (HtmlElement elIn in elemsIn) { if (elIn.GetAttribute("className").Equals("company_info_text")) { if (elIn.Children.Count == 10) { strtyTel = elIn.Children[2].InnerText.Trim().Replace("电话: ", ""); strtyEmail = elIn.Children[3].InnerText.Trim().Replace("邮箱: ", ""); strtyUrl = elIn.Children[5].InnerText.Trim().Replace("网址: ", ""); } if (elIn.Children.Count == 11) { strtyTel = elIn.Children[3].InnerText.Trim().Replace("电话: ", ""); strtyEmail = elIn.Children[3].InnerText.Trim().Replace("邮箱: ", ""); strtyUrl = elIn.Children[6].InnerText.Trim().Replace("网址: ", ""); } } T_Web_TianYanCha_POI ty = new T_Web_TianYanCha_POI(); if (elIn.GetAttribute("className").Equals("row b-c-white company-content")) { HtmlElementCollection els = elIn.Children[0].Children[0].Children; ty.Name = item.Value; if (els.Count > 1) { ty.LegalPersonName = els[1].Children[0].Children[0].Children[0].InnerText; } ty.Tel = strtyTel; ty.Email = strtyEmail; HtmlElementCollection elss = elIn.Children[0].Children[0].Children; if (!string.IsNullOrEmpty(ty.Email)) { m_pois.AddLast(ty); } if (TaskProcessor.IsFirst) { DataTable dt = GetDataTable(m_pois); Excel.DataTableToExcel(savepath, dt); m_pois.Clear(); dt.Rows.Clear(); TaskProcessor.IsFirst = false; //Excel.TableToExcelForXLSX(dt, savepath, m_strkeyword, m_intcount); //ExcelSavePOI(); } else { DataTable dt = GetDataTable(m_pois); Excel.DataTableToExcel(savepath, dt, true); m_pois.Clear(); dt.Clear(); } m_intcount++; TaskProcessor.Progress = string.Format("关键字:{0};收集数量:{1}", m_strkeyword, m_intcount); break; } } } } if (TaskProcessor.Complete) { break; } } #endregion }
public void setBoard() { doc = browser.Document as HtmlDocument; HtmlElementCollection options = doc.GetElementsByTagName("Option"); int removeCount = 0; for (int i = 0; i < options.Count; i++) { if (options[i].InnerText.IndexOf("Survey") != -1) removeCount++; else if (options[i].InnerText.IndexOf("Open Study") != -1) removeCount++; else if (options[i].InnerText.IndexOf("Organizations") != -1) removeCount++; else if (options[i].InnerText.IndexOf("Show All") != -1) removeCount++; else if (options[i].InnerText.IndexOf("Institution Only") != -1) removeCount++; else if (options[i].InnerText.IndexOf("Courses Only") != -1) removeCount++; else if (options[i].InnerText.IndexOf("UNIST") != -1) removeCount++; } board = new BBBoard[options.Count - removeCount]; int j = 0; for (int i = 0; i < options.Count; i++) { string n = options[i].InnerText.Replace("-", ""); // Open Study 제외 if (n.IndexOf("Open Study") != -1 || n.IndexOf("Organizations") != -1 || n.IndexOf("Survey") != -1 || n.IndexOf("Show All") != -1 || n.IndexOf("Institution Only") != -1 || n.IndexOf("Courses Only") != -1 || n.IndexOf("UNIST") != -1) { j++; continue; } board[i - j] = new BBBoard(); board[i - j].url = options[i].OuterHtml.Split('=')[1].Split('>')[0]; board[i - j].name = n; } }
public override void Process(HtmlDocument doc) { Processed = true; if (MemberType == Type.TopCategory) { // get level 0 links foreach (HtmlElement el in doc.GetElementsByTagName("a")) { if (el.GetAttribute("className") == "cat_t_linkto") { String name = el.InnerText; String url = el.GetAttribute("href"); Children.Add(new Category(name, url, false)); // DEBUG!!! break; } } } else { // check sub categories HtmlElement div = null; foreach (HtmlElement x in doc.GetElementsByTagName("div")) { if (x.GetAttribute("className") == "choose_subcategory") { div = x; break; } } if (div != null) { int c = 0; // process sub categories foreach (HtmlElement a in div.GetElementsByTagName("a")) { String url = a.GetAttribute("href"); HtmlElementCollection nc = a.GetElementsByTagName("div"); String name = nc[0].InnerText; // DEBUG!!! if (c++ == 1) { Children.Add(new Category(name, url, false)); break; } } } else { // process products foreach (HtmlElement pd in doc.GetElementsByTagName("div")) { if (pd.GetAttribute("className") == "cop_title") { HtmlElement a = pd.GetElementsByTagName("a")[0]; String name = a.InnerText; String url = a.GetAttribute("href"); Children.Add(new Leaf(name, url)); // DEBUG!!! break; } } // DEBUG!!! //return; // process paginator HtmlElement paginator = doc.GetElementById("paginator1"); bool checkNext = false; foreach (HtmlElement span in paginator.GetElementsByTagName("span")) { if (span.FirstChild.TagName.ToLower() == "strong") { checkNext = true; } else if (span.FirstChild.TagName.ToLower() == "a") { if (checkNext) { Processed = false; Url = (new Uri(new Uri(Url), span.FirstChild.GetAttribute("href"))).ToString(); break; } } else { throw new Exception("wwww"); } } } } }
public void getCourceMenu() { // http://bb.unist.ac.kr/webapps/blackboard/content/courseMenu.jsp?course_id=_11194_1&newWindow=true&openInParentWindow=true&refreshCourseMenu=true for (int i = 0; i < board.Count(); i++) { string url = "http://bb.unist.ac.kr/webapps/blackboard/content/courseMenu.jsp?course_id=" + board[i].url; browser.Navigate(url); while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } doc = browser.Document as HtmlDocument; HtmlElementCollection options = doc.GetElementsByTagName("Option"); HtmlElement elements = ElementsByClass(doc, "courseMenu").ElementAt(0); HtmlElementCollection lists = elements.GetElementsByTagName("li"); HtmlElementCollection a = elements.GetElementsByTagName("a"); board[i].menu = new List<string>(); board[i].menuUrl = new List<string>(); for (int j = 0; j < lists.Count; j++) { board[i].menu.Add(lists[j].InnerText); board[i].menuUrl.Add(a[j].GetAttribute("href")); } } addCourseMenu(); }
/// <summary> /// Called by the thread.start to set up for filling the DOM tree /// </summary> /// <param name="elemColl">HTMLElement collection with the "HTML" tag as its root</param> /// <remarks>Has to be passed as an object for the ParameterizedThreadStart</remarks> private void DisplayInTree(HtmlDocument docResponse) { HtmlElementCollection elemColl = docResponse.GetElementsByTagName("html"); tvDocument.Nodes.Clear(); TreeNode rootNode = new TreeNode("Web response"); rootNode.Tag = -1; tvDocument.Nodes.Add(rootNode); FillDomTree(elemColl, rootNode, 0); }
// callback function to get the content of page in the WebBrowser control public void getHtmlResult(int count) { // unequal means the content is not stable if (owner.navigationCounter != count) { return; } // get HTML content owner.htmlResult = owner.ieBrowser.DocumentText; forms.HtmlDocument doc = owner.ieBrowser.Document; if (doc.Cookie != null) { // get cookies owner.htmlCookieTable = "<table border=1 cellspacing=0 cellpadding=2><tr><th>Name</th><th>Value</th><tr>"; foreach (string cookie in Regex.Split(doc.Cookie, @";\s*")) { string[] arr = cookie.Split(new char[] { '=' }, 2); owner.htmlCookieTable += string.Format("<td>{0}</td><td>{1}</td></tr>", arr[0], (arr.Length == 2) ? arr[1] : " "); } owner.htmlCookieTable += "</table><p />"; } forms.HtmlElementCollection inputs = doc.GetElementsByTagName("INPUT"); if (inputs.Count != 0) { // get ids, names, values and types of input elements owner.htmlInputTable = "<table border=1 cellspacing=0 cellpadding=2><tr><th>Id</th><th>Name</th><th>Value</th><th>Type</th><tr>"; foreach (forms.HtmlElement input in inputs) { owner.htmlInputTable += string.Format("<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>", input.GetAttribute("Id"), input.GetAttribute("Name"), input.GetAttribute("Value"), input.GetAttribute("Type")); } owner.htmlInputTable += "</table><p />"; owner.htmlInputTable = owner.htmlInputTable.Replace("<td></td>", "<td> </td>"); } forms.HtmlElementCollection scripts = doc.GetElementsByTagName("SCRIPT"); if (scripts.Count != 0) { string vars = string.Empty; foreach (forms.HtmlElement script in scripts) { if (script.InnerHtml == null) { continue; } foreach (string name in getVariableNames(script.InnerHtml).Split(new char[] { ';' })) { if (name.Trim().Length == 0) { continue; } if (vars.Contains("\"" + name + "\"")) { continue; } // one row of the script variable table - <tr>getValue([script variable name]</tr> - getValue() is a script function in JScript.js vars += string.Format("+\"<tr>\"+getValue(\"{0}\")+\"</tr>\"", name); } } // request script to send back the names, values and types of script variables doc.InvokeScript("setTimeout", new object[] { scriptPattern.Replace("{0}", vars.Substring(1)), 10 }); } else { // set resultEvent to let main thread continue owner.resultEvent.Set(); } }
//在主页点击其它标记 public bool ClickItemByItem(IntPtr hwnd, HtmlDocument doc, HtmlElement visitItem) { Point p = GetOffset(visitItem); doc.Window.ScrollTo(0, p.Y); p.Y -= doc.GetElementsByTagName("HTML")[0].ScrollTop; Rectangle rect = wbElementMouseSimulate.GetElementRect(doc.Body.DomElement as mshtml.IHTMLElement, visitItem.DomElement as mshtml.IHTMLElement); p.X = rect.Left + rect.Width / 4; p.Y = rect.Top + rect.Height / 4; RandMove(hwnd, 500, rect); ClickOnPointInClient(hwnd, p); //ClickOnPoint(hwnd, p); return true; }
private bool RetrieveTotal(HtmlDocument doc, MoneyDatabaseUpdater dbUpdater) { double earn = 0; double left = 0; foreach (HtmlElement eleTd in doc.GetElementsByTagName("h3")) { string textTotal = eleTd.InnerText; if (eleTd.InnerText.Contains("总金额")) { left = this.GetAmountFromText(eleTd.InnerText); } else if (eleTd.InnerText.Contains("历史累计收益")) { earn = this.GetAmountFromText(eleTd.Parent.GetElementsByTagName("div")[0].InnerText); } } this._message = string.Format("今日\r\n余额:{0}元\r\n累计收益:{1}元", left, earn); dbUpdater.AddTotal(DateTime.Now, earn, left); return true; }
/// <summary> /// Static method to parse the current <see cref="HtmlDocument"/> of the /// <see cref="WebBrowser"/> for its maximal scrollsize. /// Returns the maximum of the given scrollsize and the documents scrollsize. /// So be sure to reset current srollsize first. /// </summary> /// <param name="document"> The <see cref="HtmlDocument"/> to check its maximal size. /// </param> /// <param name="currentScrollsize"> Ref. A <see cref="Size"/> to be updated with /// maximal scroll size values. /// </param> private static void GetMaxScrollSizeOfDocument(HtmlDocument document, ref Size currentScrollsize) { if (document.GetElementsByTagName("HTML").Count > 0 && document.Body != null) { int htmlWidth = document.GetElementsByTagName("HTML")[0].ScrollRectangle.Width; int htmlHeight = document.GetElementsByTagName("HTML")[0].ScrollRectangle.Height; if (document.Body != null) { int scrollWidth = document.Body.ScrollRectangle.Width; int scrollHeight = document.Body.ScrollRectangle.Height; int maxWidth = Math.Max(htmlWidth, scrollWidth); int maxHeight = Math.Max(htmlHeight, scrollHeight); currentScrollsize.Width = Math.Max(currentScrollsize.Width, maxWidth); currentScrollsize.Height = Math.Max(currentScrollsize.Height, maxHeight); } } }
public override void Process(HtmlDocument doc) { Processed = true; HtmlElement details = null; bool hasAddress = false; bool hasDetails = false; foreach (HtmlElement div in doc.GetElementsByTagName("div")) { String cn = div.GetAttribute("className"); if (cn == "cop_address") { Address = div.InnerText; hasAddress = true; } else if (cn == "cop_contact_inf") { details = div; hasDetails = true; } if (hasAddress && hasDetails) break; } // process details foreach (HtmlElement li in details.GetElementsByTagName("li")) { String cname = li.FirstChild.GetAttribute("className"); if (cname == "call_i") { Phones.Add(li.Children[1].InnerText.Trim()); } else if (cname == "web_i") { Sites.Add(li.Children[1].InnerText.Trim()); } else { MessageBox.Show(Url.ToString() + ": " + cname); } } // coordinates MatchCollection matches = Regex.Matches(doc.Body.InnerHtml, "google\\.maps\\.LatLng\\((.*?)\\)"); if (matches.Count > 0) { Coords = matches[0].Groups[1].Value; } }
private string DetermineFavIconUrl(HtmlDocument htmlDocument) { var links = htmlDocument.GetElementsByTagName("link"); var favIconLink = links.Cast<HtmlElement>() .SingleOrDefault(x => x.GetAttribute("rel").ToLowerInvariant() == "shortcut icon"); if (favIconLink != null) { var href = favIconLink.GetAttribute("href"); var favIconUrl = htmlDocument.Url.AbsoluteUri.Replace(htmlDocument.Url.PathAndQuery, href); return favIconUrl; } return null; }
public static void Calc(HtmlDocument doc, DataSet ds, Dictionary<string, InvokeResult> invokes) { Dictionary<string, double> dictionary = new Dictionary<string, double>(); foreach (string str in tags) { HtmlElementCollection elementsByTagName = doc.GetElementsByTagName(str); foreach (HtmlElement element in elementsByTagName) { string attribute = element.GetAttribute("sfcategory"); if (!string.IsNullOrEmpty(attribute)) { string format = element.GetAttribute("format"); if ((format == null) || (format.Length == 0)) { format = "0.00"; } LoggingService.DebugFormatted("计算税费:{0}", new object[] { element.GetAttribute("dbcolumn") }); double? nullable = UseGetDataCalc(doc, ds, element, invokes); if (!nullable.HasValue) { nullable = HtmlElementCalc(doc, element, invokes); } if (nullable.HasValue) { if (format.LastIndexOf('.') >= 0) { nullable = new double?(MathHelper.Round(nullable.Value, (format.Length - format.LastIndexOf('.')) - 1)); } else { nullable = new double?(MathHelper.Round(nullable.Value, 0)); } SetHtmlElementValue(element, nullable.Value.ToString(format)); nullable = new double?(Convert.ToDouble(nullable.Value.ToString(format))); if (element.GetAttribute("type") != "hidden") { string[] strArray = attribute.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string str4 in strArray) { Dictionary<string, double> dictionary2; string str5; if (!dictionary.ContainsKey(str4)) { dictionary.Add(str4, 0.0); } (dictionary2 = dictionary)[str5 = str4] = dictionary2[str5] + nullable.Value; } } } else { SetHtmlElementValue(element, string.Empty); } } } } foreach (KeyValuePair<string, double> pair in dictionary) { HtmlElement elementById = doc.GetElementById(pair.Key); if (elementById != null) { SetHtmlElementValue(elementById, pair.Value.ToString("0.00")); } } }