// System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser(); private async void Border_MouseDown_1(object sender, MouseButtonEventArgs e) { if (Email.Text != string.Empty || PSW.Password != string.Empty) { wb.Navigate("http://ui.ptlogin2.qq.com/cgi-bin/login?appid=1006102&s_url=http://id.qq.com/index.html&hide_close_icon=1"); rk.Text = "登录中..."; await Task.Delay(2000); System.Windows.Forms.HtmlDocument doc = wb.Document; doc.GetElementById("switcher_plogin").InvokeMember("click"); await Task.Delay(200); doc.GetElementById("u").InnerText = Email.Text; await Task.Delay(200); doc.GetElementById("p").InnerText = PSW.Password; await Task.Delay(200); doc.GetElementById("login_button").InvokeMember("click"); await Task.Delay(1000); if (wb.DocumentTitle != "我的QQ中心" || !wb.DocumentText.Contains("安全验证")) { rk.Text = "登录失败,请检查账号和密码."; } else if (wb.DocumentText.Contains("安全验证")) { op.IsOpen = true; rk.Text = "请输入验证码"; } } }
// this is how you will send info to the webpage firstly to setup the automatic send web info private void btnTest_Click(object sender, EventArgs e) { System.Windows.Forms.HtmlDocument doc = webBrowser1.Document; try { HtmlElement username = doc.GetElementById(txtBUserElementID.Text); HtmlElement password = doc.GetElementById(txtBPassElementID.Text); HtmlElement submit = doc.GetElementById(txtBLoginElementID.Text); if (!checkBoxjustButtonClick.Checked) { username.SetAttribute("value", txtBUsername.Text); password.SetAttribute("value", txtBPassword.Text); } submit.InvokeMember("click"); } catch (Exception) { listBoxErrors.Items.Add(DateTime.Now.ToLongTimeString() + " " + "ERROR Could Not Send command to web page !!"); // MessageBox.Show(ex.Message, "m3"); //throw; } }
public void ScrapePage(HtmlDocument link) { CurrentDoc = link; TableData.Add(CurrentDoc.GetElementById("ctl00_cphBody_repeaterOwnerInformation_ctl00_lblOwnerName").InnerText); TableData.Add(CurrentDoc.GetElementById("ctl00_cphBody_lblHeaderPropertyAddress").InnerText); ScrapeHTMLTables("buildingsDetailWrapper", "table", 0); ScrapeHTMLTables("buildingsDetailWrapper", "table", 1); ScrapeHTMLTables("buildingsDetailWrapper", "table", 3); RemoveUnneededListElements(); }
// public class CloseDetector // { private void Detector() //ExtendedWebBrowser ewb) { while (true && !closing) { try { //MessageBox.Show("get document!" + this + " : " + uiDocument); //var document = wb.Document; //MessageBox.Show("got document! " + document); var idselectDone = uiDocument.GetElementById("idselectDone"); //MessageBox.Show("IN LOOP! " + " : " + idselectDone); if (idselectDone != null) { //closing = true; //MessageBox.Show("Closing!"); closing = true; } else { Thread.Sleep(200); } } catch (Exception e) { MessageBox.Show("Detector Exception : " + e); closing = true; } // } Closing(this, EventArgs.Empty); }
public virtual void NotifyScreenOk(System.Windows.Forms.HtmlDocument argDoc) { if (!string.IsNullOrEmpty(m_targetName)) { m_targetElement = argDoc.GetElementById(m_targetName); } if (!string.IsNullOrEmpty(m_targetTextName)) { m_targetTextElement = argDoc.GetElementById(m_targetTextName); } if (null == m_targetElement) { m_targetElement = m_storyBoard.TargetElement; if (null != m_targetElement) { m_targetName = m_storyBoard.TargetName; } } }
// DocumentCompleted event handle void IEBrowser_DocumentCompleted(object sender, forms.WebBrowserDocumentCompletedEventArgs e) { forms.HtmlDocument doc = ((forms.WebBrowser)sender).Document; if (doc.Title.Equals("Welcome to Windows Live") && loginCount++ < 3) { // set email address and password, and try to login three times try { doc.GetElementById("i0116").SetAttribute("value", userName); } catch { ieBrowser.Navigate("http://login.live.com/#"); return; } doc.GetElementById("i0118").SetAttribute("value", password); doc.GetElementById("idSIButton9").InvokeMember("click"); } else { // request jscript to call c# callback function with a parameter of navigation counter doc.InvokeScript("setTimeout", new object[] { string.Format("window.external.getHtmlResult({0})", navigationCounter), 10 }); } }
protected void SetFileUpload(HtmlDocument document, string name, string fileName) { var fileElement = (HTMLInputElement)document.GetElementById(name).DomElement; fileElement.focus(); // The first space is to open the file open dialog. The // remainder of the spaces is to have some messages for // until the open dialog actually opens. SendKeys.SendWait(" " + fileName + "{ENTER}"); }
/// <summary> /// 返回指定WebBrowser中图片<IMG></IMG>中的图内容 /// </summary> /// <param name="webCtl">WebBrowser控件</param> /// <param name="imgeTag">IMG元素</param> /// <returns>IMG对象</returns> private Image GetWebImage(WebBrowser webBrowser, string imgeTagId) { System.Windows.Forms.HtmlDocument winHtmlDoc = webBrowser.Document; HTMLDocument doc = (HTMLDocument)winHtmlDoc.DomDocument; HtmlElement imgTag = winHtmlDoc.GetElementById(imgeTagId); HTMLBody body = (HTMLBody)doc.body; IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange(); IHTMLControlElement imgE = (IHTMLControlElement)imgTag.DomElement; //图片地址 rang.add(imgE); rang.execCommand("Copy", false, null); //拷贝到内存 Image numImage = Clipboard.GetImage(); return(numImage); }
//******************************************************************************************** private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (server.UseHtmlLogin) { if (!tryAutoLogin) { return; } System.Windows.Forms.HtmlDocument document = webBrowser.Document; try { HtmlElement user = document.GetElementById(server.HtmlUserBox); if (user != null) { user.InnerText = server.Username; } HtmlElement pass = document.All[server.HtmlPassBox]; if (pass != null) { pass.InnerText = server.Password; HtmlElement login = document.All[server.HtmlLoginBtn]; if (login != null) { login.InvokeMember("click"); tryAutoLogin = false; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
private void ActionsBuilderWebView_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { // Set common properties (name, is scene or object, etc.) _document = ActionsBuilderWebView.Document; _document.GetElementById("ActionsBuilderObjectName").SetAttribute("value", _objectName); if (isRootNode) _document.InvokeScript("setIsScene"); else _document.InvokeScript("setIsObject"); _document.InvokeScript("updateObjectName"); if (getProperty()) { _document.GetElementById("ActionsBuilderJSON").SetAttribute("value", _jsonResult); _document.InvokeScript("updateGraphFromJSON"); } // Set lists of meshes, lights, cameras etc. var gameScene = Loader.Global.IGameInterface; gameScene.InitialiseIGame(false); var meshes = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Mesh); fillObjectsList(meshes, "setMeshesNames"); var lights = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Light); fillObjectsList(lights, "setLightsNames"); var cameras = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Camera); fillObjectsList(cameras, "setCamerasNames"); fillSoundsList(meshes, "setSoundsNames"); // Need to subclass this, then allow 3ds Max usage //Win32.SubClass(this.ActionsBuilderWebView.Handle); }
private void WEBUI_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { mDocument = webUI.GetDocument(); int index = webUI.GetViewIndex(); switch(index) { case VIEW_HOME: edRuleFile = mDocument.GetElementById("rule-file"); edBookmarkFile = mDocument.GetElementById("bookmark-file"); HtmlElement btnRuleFile = mDocument.GetElementById("btn-rule-file"); HtmlElement btnBookmarkFile = mDocument.GetElementById("btn-bookmark-file"); HtmlElement btnClassfiy = mDocument.GetElementById("btn-classfiy"); btnRuleFile.Click += new HtmlElementEventHandler(OnRuleFileClick); btnBookmarkFile.Click += new HtmlElementEventHandler(OnBookmarkFileClick); btnClassfiy.Click += new HtmlElementEventHandler(OnClassfiyClick); break; case VIEW_PROCESS: txtPinText = mDocument.GetElementById("pin-text"); HtmlElement btnExport = mDocument.GetElementById("btn-export"); btnExport.Click += new HtmlElementEventHandler(OnExportClick); break; } webUI.SetLoadStatus(true); }
private void ChangeTicket(HtmlDocument doc, TicketOrder ticketOrder) { HtmlElement element = doc.GetElementById("tTicketPrice"); if (element != null) { string sql = "select * from t_to_order_tickets where order_id=" + order_Id + " and rownum<2"; DataTable dt = DSCRM.DBA.GetDataTable(sql); double YPrice = Convert.ToInt32(dt.Rows[0]["FULL_PRICE"].ToString()); doc.GetElementById("tTicketPrice100").SetAttribute("value", YPrice.ToString());//ȫ�� //Ʊ�� double enPrice = 10 * RoundFloat1(YPrice * 0.05, 0); double babyPrice = 10 * RoundFloat1(YPrice * 0.01, 0); element.SetAttribute("value", (ticketOrder.TicketPassengers[0].TicketPrice + "|" + enPrice + "|" + babyPrice)); //�ۿ� doc.GetElementById("tRate").SetAttribute("value", ticketOrder.TicketPassengers[0].Rate.ToString() + "|50|10"); //���� doc.GetElementById("tAirportTax").SetAttribute("value", ticketOrder.TicketPassengers[0].AirPortTax.ToString() + "|0|0"); //ȼ�� double enFuelTax = GetInfFlueTax(ticketOrder.TicketPassengers[0].FuelTax); doc.GetElementById("tFuelTax").SetAttribute("value", ticketOrder.TicketPassengers[0].FuelTax.ToString() + "|" + enFuelTax + "|0"); //Ԥ������ element = doc.GetElementById("hidBookingParam"); string hidStr = "<xml><Arguments><CommDefID>-1</CommDefID><CommisionRate>-1</CommisionRate><Discount>" + dt.Rows[0]["DISCOUNT"] + "</Discount><TicketPrice>" + YPrice + "</TicketPrice><AirPortTax>" + ticketOrder.TicketPassengers[0].AirPortTax + "</AirPortTax><FuelTax>" + ticketOrder.TicketPassengers[0].FuelTax + "</FuelTax><IsSpecial>0</IsSpecial></Arguments></xml>"; //����˿� string[] Passengers = doc.GetElementById("t_PassengerList").GetAttribute("value").Split(','); string NewPassengerList = ""; for (int i = 0; i < Passengers.Length - 1; i++) { string[] subGuest = Passengers[i].Split('|'); NewPassengerList += subGuest[0] + "|"; NewPassengerList += subGuest[1] + "|"; NewPassengerList += subGuest[2] + "|"; NewPassengerList += subGuest[3] + "|"; if (subGuest[2] == " ���� ") { NewPassengerList += ticketOrder.TicketPassengers[0].TicketPrice + "|"; NewPassengerList += ticketOrder.TicketPassengers[0].AirPortTax + "|"; NewPassengerList += ticketOrder.TicketPassengers[0].FuelTax + ","; } else if (subGuest[2] == " ��ͯ ") { NewPassengerList += enPrice + "|"; NewPassengerList += "0|"; NewPassengerList += enFuelTax + ","; } else if (subGuest[2] == " Ӥ�� ") { NewPassengerList += babyPrice + "|"; NewPassengerList += "0|"; NewPassengerList += "0,"; } } doc.GetElementById("t_PassengerList").SetAttribute("value", NewPassengerList); (doc.DomDocument as IHTMLDocument2).parentWindow.execScript("AutoPrice();", "javascript"); } }
private void ChangeData(HtmlDocument doc, TicketOrder ticketOrder) { #region ��������Ϣ doc.GetElementById("tSendContactName").SetAttribute("value", ticketOrder.DeliverRecord.Contact_Name == null ? "" : ticketOrder.DeliverRecord.Contact_Name); //��ϵ�� doc.GetElementById("tSendTel").SetAttribute("value", ticketOrder.DeliverRecord.Contact_Phone == null ? "" : ticketOrder.DeliverRecord.Contact_Phone); //��ϵ�˵绰 doc.GetElementById("tSendMobile").SetAttribute("value", ticketOrder.DeliverRecord.Contact_Mobile == null ? "" : ticketOrder.DeliverRecord.Contact_Mobile); //��ϵ���ֻ� doc.GetElementById("tSendEmail").SetAttribute("value", ticketOrder.DeliverRecord.Contact_Email == null ? "" : ticketOrder.DeliverRecord.Contact_Email); //��ϵ���ʼ� doc.GetElementById("tSendAddress").SetAttribute("value", ticketOrder.DeliverRecord.Contact_Address == null ? "" : ticketOrder.DeliverRecord.Contact_Address); //��ϵ��ַ doc.GetElementById("tCustomerRemark").SetAttribute("value", ticketOrder.CustomerRemark == null ? "" : ticketOrder.CustomerRemark); //�ͻ�����Ҫ�� doc.GetElementById("tCompanyRemark").SetAttribute("value", ticketOrder.CompanyRemark == null ? "" : ticketOrder.CompanyRemark); //��˾������ע doc.GetElementById("tSentDate").SetAttribute("value", ticketOrder.GetTicketTime == null ? "" : ticketOrder.GetTicketTime); //��Ʊʱ�� doc.GetElementById("ddlOperDstSite").SetAttribute("value", ticketOrder.DstSite); //��Ʊ�� string sIssueCityCode = TicketOrderAdmin.GetCityCodebyPartnerID(ticketOrder.DstSite); doc.GetElementById("ddlOperDstCity").SetAttribute("value", sIssueCityCode); //������id //doc.GetElementById("ddlSendType").SetAttribute("value", ticketOrder.DeliverRecord.Deliver_Type_Id.ToString());//���ͷ�ʽ HtmlElementCollection elements = doc.GetElementById("ddlSendType").GetElementsByTagName("Option"); foreach (HtmlElement el in elements) { if (el.GetAttribute("value") == ticketOrder.DeliverRecord.Deliver_Type_Id.ToString()) { el.SetAttribute("selected", "selected"); } } if (ticketOrder.IsRemitSMS) doc.GetElementById("ckbRemitSMS").InvokeMember("click"); //�Ƿ������ if (ticketOrder.IsNotShouldIssue) doc.GetElementById("ckbNotIssue").InvokeMember("click"); //�Ƿ���Ҫ��Ʊ if (ticketOrder.SendIndex == 0) doc.GetElementById("cbSendIndex").InvokeMember("click"); //�Ƿ���Ҫ�Ӽ� doc.GetElementById("txtUserFixMoney").SetAttribute("value", ticketOrder.MemberBalance.ToString() == null ? "" : ticketOrder.MemberBalance.ToString()); //�������տ� doc.GetElementById("txtArrearage").SetAttribute("value", ticketOrder.PayOweAmount.ToString() == null ? "" : ticketOrder.PayOweAmount.ToString()); //�������տ� doc.GetElementById("txtPayAmount").SetAttribute("value", ticketOrder.PayAmount.ToString());//֧����� doc.GetElementById("txtArrearage").SetAttribute("value", ticketOrder.PayOweAmount.ToString()); //֧��Ƿ�� if (ticketOrder.Pay_Type == EnumDef.ETicketOrderPayType.��˾����֧��) { doc.GetElementById("rblPayType_0").InvokeMember("click"); doc.GetElementById("ddlJSJPayType").SetAttribute("value", "4"); } else if (ticketOrder.Pay_Type == EnumDef.ETicketOrderPayType.��˾�������п�) { doc.GetElementById("rblPayType_0").InvokeMember("click"); doc.GetElementById("ddlJSJPayType").SetAttribute("value", "8"); doc.GetElementById("ddlUnionPay").SetAttribute("value", (ticketOrder.IsUnionCard == EnumDef.ETicketOrderUnionPay.�� ? "1" : "2")); } else if (ticketOrder.Pay_Type == EnumDef.ETicketOrderPayType.��Ʊ�������ֽ�) { doc.GetElementById("rblPayType_1").InvokeMember("click"); doc.GetElementById("ddlSelfPayType").SetAttribute("value", "1"); } else if (ticketOrder.Pay_Type == EnumDef.ETicketOrderPayType.��Ʊ������ֽ�) { doc.GetElementById("rblPayType_2").InvokeMember("click"); doc.GetElementById("ddlInsteadPayType").SetAttribute("value", "1"); if (ticketOrder.TicketPayInfo != null) { doc.GetElementById("ddlInsteadPartner").SetAttribute("value", ticketOrder.TicketPayInfo.GatherPartnerId.ToString()); } } F_Debit_Payment_Record mobilePayRecord = new F_Debit_Payment_Record(); if (mobilePayRecord.Load(order_Id, EnumDef.ESPOrderType.��Ʊ����)) { doc.GetElementById("rblPayType_0").InvokeMember("click"); if (mobilePayRecord.PaymentTypeId == EnumDef.ETMobliePay.��ǿ�֧��) { doc.GetElementById("ddlJSJPayType").SetAttribute("value", "8"); doc.GetElementById("ddlUnionBank").SetAttribute("value", mobilePayRecord.BankcardTypeId.Value.ToString()); doc.GetElementById("txtUnionCardNO").SetAttribute("value", mobilePayRecord.CashcardNo.Trim()); doc.GetElementById("txtUnionPhone").SetAttribute("value", mobilePayRecord.CashcardMobi.Trim()); } else if (mobilePayRecord.PaymentTypeId == EnumDef.ETMobliePay.���ÿ�֧��) { doc.GetElementById("ddlJSJPayType").SetAttribute("value", "3"); doc.GetElementById("ddlCreditCardType").SetAttribute("value", mobilePayRecord.CreditcardType.Value.ToString()); doc.GetElementById("txtCreditCardNum").SetAttribute("value", mobilePayRecord.CreditcardNo.Trim()); doc.GetElementById("txtCreditCardDate").SetAttribute("value", mobilePayRecord.CreditcardAvail.Value.ToString("yyyy-MM-dd")); doc.GetElementById("txtHandName").SetAttribute("value", mobilePayRecord.CreditcardOwner); if (mobilePayRecord.CreditcardCvv2 != null && mobilePayRecord.CreditcardCvv2.Trim() != "") { HtmlElement element = doc.GetElementById("tCompanyRemark"); element.SetAttribute("value", element.GetAttribute("value") + "CVV" + mobilePayRecord.CreditcardCvv2); } } } #endregion }
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { document = this.webBrowser.Document; HtmlElement btnSubmit = document.GetElementById("btnSubmit"); if (btnSubmit != null) { btnSubmit.Click += new HtmlElementEventHandler(btnSubmit_Click); } this.Cursor = Cursors.Default; }
private void LoginSupportedByWangWang(HtmlDocument doc) { HtmlElement ele1 = doc.GetElementById("J_Static2Quick"); HtmlElement ele2 = doc.GetElementById("J_SubmitQuick"); HtmlElement ele3 = doc.GetElementById("J_OtherAccountV"); //使用其他账户登录 HtmlElement ele4 = doc.GetElementById("ra-0"); string ss = string.Empty; ss += ele1 == null ? "false, " : "J_Static2Quick, "; ss += ele2 == null ? "false, " : "J_SubmitQuick, "; ss += ele3 == null ? "false, " : "J_OtherAccountV, "; ss += ele4 == null ? "false" : "ra-0"; Console.Out.WriteLine(ss); HtmlElement ele = null; if (ele2 == null && ele3 == null) { ele = ele1; } else if (ele1 == null && ele3 == null) { ele = ele2; // Although WebBrowser.DocumentCompleted event risen // The entire page is not ready, maybe because of some AJAX content // Ignore in this case if(ele4 == null) { ele = null; } } else if (ele1 == null && ele2 == null) { ele = ele3; } else { MessageBox.Show(ss); } if (ele != null) { ele.InvokeMember("click"); } }
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 void webBrowserAg_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { string urlAdd = "https://rd.tencent.com/top/ptlogin/ptlogins/login?site="; string urlAdd2 = "https://tapd.tencent.com/ptlogin/ptlogins/login?"; if ((webBrowserAg.Url != null && webBrowserAg.Url.ToString().Contains(urlAdd)) || (webBrowserAg.Url != null && webBrowserAg.Url.ToString().Contains(urlAdd2))) { //判断是否已加载完网页 if (webBrowserAg.ReadyState == WebBrowserReadyState.Complete) { //获取网页文档对象,相当于获取网页的全部源码 HtmlDocument htmlDoc = this.webBrowserAg.Document; //设置帐号 HtmlElement id = htmlDoc.GetElementById("username"); id.SetAttribute("value", UserName); //设置密码 HtmlElement pwd = htmlDoc.GetElementById("password_input"); pwd.SetAttribute("value", PassWord); //登录 HtmlElement btn = htmlDoc.GetElementById("login_button"); if (btn != null) { btn.InvokeMember("click"); } } } string urlCheckOut = "http://om.tencent.com/attendances/check_out"; string urlCheckIn = "https://rd.tencent.com/outsourcing/attendances/add"; if (webBrowserAg.Url != null) { if (webBrowserAg.Url.ToString().Contains(urlCheckOut) || webBrowserAg.Url.ToString().Contains(urlCheckIn)) { //判断是否已加载完网页 if (webBrowserAg.ReadyState == WebBrowserReadyState.Complete) { HtmlDocumentAgilityPack htmlDoc1 = new HtmlDocumentAgilityPack(); htmlDoc1.LoadHtml(webBrowserAg.DocumentText); string txt = ""; try { txt = htmlDoc1.DocumentNode.SelectSingleNode(@"./html[1]/body[1]/div[3]/div[1]/div[1]/div[4]/div[1]/p[1]/span[1]").InnerText.TrimEnd(); } catch (Exception) { } if (txt != string.Empty) { DateTime LastCheckInTime; try { FrmSet.lastCheckInTime = FrmSet.CheckInTime = LastCheckInTime = DateTime.ParseExact(txt, "yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InvariantCulture); Share.wFiles.WriteString("WCO", "LastSignInTime", string.Format("{0:yyyy-MM-dd HH:mm:ss}", LastCheckInTime)); webBrowserAg.Dispose(); } catch (Exception) { webBrowserAg.Dispose(); } } } } } }
private static string ParseSingeString(HtmlDocument doc, DataSet ds, string result, Dictionary<string, InvokeResult> invokes) { double num; if (!double.TryParse(result, out num)) { Expression expression; int num2; if (result.EndsWith("%") && double.TryParse(result.Substring(0, result.Length - 1), out num)) { return result; } if (result.Equals("''")) { return string.Empty; } string[,] strArray = ParseTableAndColumn(result, new char[] { '|', '#' }); if (TryParseExpression(strArray[0, 0], out expression)) { double num3; for (num2 = 1; num2 < strArray.GetLength(0); num2++) { object obj2; if (TryParseColumnValue(ds, strArray[num2, 0], strArray[num2, 1], out obj2)) { expression.Parameters["p" + num2.ToString()] = obj2; } else { LoggingService.WarnFormatted("无法为表达式:{0}中参数:p{1} 获取 {2}.{3} 的值,可能其为空值或找不到表或列,无法计算,所以返回零值", new object[] { strArray[0, 0], num2, strArray[num2, 0], strArray[num2, 1] }); return "0"; } } object obj3 = expression.Evaluate(); LoggingService.InfoFormatted("表达式:{0} 的值是: {1}", new object[] { strArray[0, 0], obj3 }); if (double.TryParse(obj3.ToString(), out num3)) { if (num3 >= 0.0) { return MathHelper.Round(num3, 2).ToString(); } return "0"; } return obj3.ToString(); } for (num2 = 0; num2 < strArray.GetLength(0); num2++) { if (ds.Tables.Contains(strArray[num2, 0]) && ds.Tables[strArray[num2, 0]].Columns.Contains(strArray[num2, 1])) { DataRow row; if (GetDataRow(ds, strArray[num2, 0], out row)) { if (row == null) { return string.Empty; } object obj4 = row[strArray[num2, 1]]; if (!(Convert.IsDBNull(obj4) || (obj4.ToString().Length <= 0))) { return obj4.ToString(); } } } else { if (strArray[0, 0] == "invoke") { return invokes[strArray[0, 1]](string.Empty).ToString(); } try { return doc.GetElementById(strArray[0, 0]).GetAttribute(strArray[0, 1]); } catch (Exception exception) { LoggingService.Error(exception); } } } } return result; }
private void button3_Click(object sender, EventArgs e) { ///统计结束前所有操作键不可用 this.button3.Enabled = false; this.button4.Enabled = false; this.button1.Enabled = false; this.button2.Enabled = false; int TotalClerksCount = 0; int TotalDeptCount = 0; try { document = webBrowser1.Document; formElement = document.GetElementById("form1"); form = (mshtml.HTMLFormElement)formElement.DomElement; deptElement = document.GetElementById("ddl_depart"); deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement); personElement = document.GetElementById("ddl_person"); personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement); btnElement = document.GetElementById("btn_Query"); btn = (mshtml.HTMLInputElement)(btnElement.DomElement); deptStringList = deptElement.OuterText.Split(new char[] { '—', ' ' }) .Where(p => p != string.Empty).Select(p => p.Trim()).ToList(); TotalDeptCount = deptStringList.Count; textBox1.Text = TotalDeptCount.ToString(); List<string> lastPersonStringList = new List<string>(); int currentDeptIndex = deptSelector.selectedIndex; for (int i = (currentDeptIndex == 0 ? currentDeptIndex : currentDeptIndex - 1); i < deptStringList.Count; i++) { bool IFailed = true; int IFailedCount = 0; while (IFailed) { try { if (WinFormClose) { break; } deptElement = document.GetElementById("ddl_depart"); deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement); formElement = document.GetElementById("form1"); form = (mshtml.HTMLFormElement)formElement.DomElement; deptSelector.selectedIndex = i + 1; deptSelector.FireEvent("onchange"); form.submit(); System.Threading.Thread.Sleep(300); Application.DoEvents(); personElement = document.GetElementById("ddl_person"); personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement); var tempPersonStringList = personElement.OuterText.Split(new char[] { '—', ' ' }) .Where(p => p != string.Empty).Select(p => p.Trim()).ToList(); personStringList = new List<string>(); //get current dept persons for (int j = 0; j < tempPersonStringList.Count; j++) { if (j % 2 == 1) personStringList.Add(tempPersonStringList[j]); } if (lastPersonStringList.Count == personStringList.Count) { if (lastPersonStringList.Count > 0) { if (lastPersonStringList[0] == personStringList[0]) { IFailed = true; } else { TotalClerksCount += personStringList.Count; IFailed = false; lastPersonStringList.Clear(); foreach (string oneName in personStringList) { lastPersonStringList.Add(oneName); } } } else if (IFailedCount > 5) { IFailed = false; } else if (lastPersonStringList.Count == 0) { IFailed = false; } } else { TotalClerksCount += personStringList.Count; textBox2.Text = TotalClerksCount.ToString(); IFailed = false; lastPersonStringList.Clear(); foreach (string oneName in personStringList) { lastPersonStringList.Add(oneName); } } } catch (Exception ex) { Trace.TraceError(ex.Message); IFailedCount++; if (IFailedCount > 5) { System.Threading.Thread.Sleep(IFailedCount * 200); Application.DoEvents(); } } } } } catch { } ///统计结束所有操作键可用 this.button3.Enabled = true; this.button4.Enabled = true; this.button1.Enabled = true; this.button2.Enabled = true; }
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 void getCars(HtmlElement elems) { String carURL = ""; String lastUrl = ""; String shortDesc = ""; String sellerAdd = ""; DateTime dtOfReg = DateTime.Now; Double mileage = 0; String power = ""; Single sPrice = 0; Single ePrice = 0; String imgLinks = ""; dbSQL dbS = new dbSQL(); List <String> Links = new List <string>(); //HtmlAgilityPack.HtmlDocument htmldoc = new HtmlAgilityPack.HtmlDocument(); //htmldoc.LoadHtml(elems.InnerHtml); //var li = htmldoc.DocumentNode.SelectNodes("href"); foreach (HtmlElement element in elems.All) { if (element.GetAttribute("className") == "article-preview") { Console.WriteLine(element.GetAttribute("href")); foreach (HtmlElement subElem in element.All) { if (subElem.GetAttribute("className") == "article-preview__name") { //Console.WriteLine("New car found"); //Console.WriteLine("Short Desc: " + subElem.InnerText); carURL = element.GetAttribute("href"); Links.Add(carURL); shortDesc = subElem.InnerText; } } } } foreach (var link in Links) { Console.WriteLine(link); //Navigate(link, this.webBrowser1); System.Net.WebClient wc = new System.Net.WebClient(); String linkx = link.Replace("about:", "https://auto.ricardo.ch"); System.IO.StreamReader webReader = new System.IO.StreamReader( wc.OpenRead(linkx)); string webPageData = webReader.ReadToEnd(); WebBrowser browser = new WebBrowser(); browser.ScriptErrorsSuppressed = true; browser.DocumentText = webPageData; browser.Document.OpenNew(true); browser.Document.Write(webPageData); browser.Refresh(); System.Windows.Forms.HtmlDocument doc = browser.Document; Console.WriteLine(doc.Body.All[0].InnerText); HtmlElement elem = getHTMLElemStr("main-content", doc); if (elem == null) { elem = doc.GetElementById("ricardo-spa"); } if (elem != null) { ePrice = 0; shortDesc = doc.Title; //power = getHtmlText(elem, "vehicle-data"); power = getHtmlText(elem, "jss300", "Leistung"); if (power == "") { power = getHtmlText(elem, "power item", ""); } power = Regex.Replace(power, "[^0-9]", ""); //String carURL = ""; //String lastUrl = ""; //String shortDesc = ""; sellerAdd = getHtmlText(elem, "article - preview__address", ""); String s = getHtmlText(elem, "mileage item", ""); if (s == "") { s = getHtmlText(elem, "jss295 jss297", "Kilometerstand"); } s = Regex.Replace(s, "[^0-9]", ""); if (s != "") { mileage = Double.Parse(s); } s = getHtmlText(elem, "mdl-typography--font-light price-no-wrap", ""); if (s == "") { s = getHtmlText(elem, "valueprice--1-nta", ""); s = Regex.Replace(s, "[^0-9.]", ""); if (s != "") { ePrice = Single.Parse(s.Replace(".", ",")); } s = getHtmlText(elem, "value--KVPJf", ""); } s = Regex.Replace(s, "[^0-9.]", ""); if (s != "") { sPrice = Single.Parse(s.Replace(".", ",")); } s = getHtmlText(elem, "registration item", "Erste"); s = Regex.Replace(s, "[^0-9]", ""); if (s.Length > 5) { String sm = s.Substring(0, 2); if (sm.Substring(0, 1) == "0") { sm = sm.Substring(1, 1); } if (Regex.IsMatch(s.Substring(2, 4), @"^\d+$")) { int y = Int32.Parse(s.Substring(2, 4)); int m = Int32.Parse(sm); dtOfReg = new DateTime(y, m, 1).Date; } } else { dtOfReg = new DateTime(1900, 1, 1).Date; } imgLinks = getHtmlText(elem, "gallery-container", ""); if (imgLinks == null || imgLinks == "") { imgLinks = getHtmlText(elem, "jss283 jss276", ""); } dbS.InsOffer(shortDesc, dtOfReg, mileage, power, sellerAdd, sPrice, ePrice, linkx, imgLinks); } } Console.WriteLine("Process finished."); }
private void LoginWithNamePassword(HtmlDocument doc) { HtmlElement ele; ele = doc.GetElementById("TPL_username_1"); ele.SetAttribute("value", "username"); ele = doc.GetElementById("TPL_password_1"); ele.SetAttribute("value", "password"); ele = doc.GetElementById("J_SubmitStatic"); ele.InvokeMember("click"); }
/********************************************************** * * 포탈 * **********************************************************/ 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); } } }
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"); } } } } }
/********************************************************** * * 예약 버튼 * **********************************************************/ private void studyReserveBtn_Click(object sender, EventArgs e) { doc = browser.Document as HtmlDocument; if (studyTimeBox.SelectedItem == null) { MessageBox.Show("사용할 시간을 선택해 주세요 :&", "Robot의 경고"); return; } doc.GetElementById("ctl00_ContentPlaceHolder_ddusehour").SetAttribute("value", studyTimeBox.SelectedItem.ToString().Substring(0, 1)); if (studyStudentId1.Text != "") doc.GetElementById("ctl00_ContentPlaceHolder_txtcompany_1").SetAttribute("value", studyStudentId1.Text); if (studyStudentId2.Text != "") doc.GetElementById("ctl00_ContentPlaceHolder_txtcompany_2").SetAttribute("value", studyStudentId2.Text); if (studyStudentId3.Text != "") doc.GetElementById("ctl00_ContentPlaceHolder_txtcompany_3").SetAttribute("value", studyStudentId3.Text); if (studyStudentId4.Text != "") doc.GetElementById("ctl00_ContentPlaceHolder_txtcompany_4").SetAttribute("value", studyStudentId4.Text); if (studyStudentId5.Text != "") doc.GetElementById("ctl00_ContentPlaceHolder_txtcompany_5").SetAttribute("value", studyStudentId5.Text); if (studyStudentId6.Text != "" && studyStudentId6.Enabled != false) doc.GetElementById("ctl00_ContentPlaceHolder_txtcompany_6").SetAttribute("value", studyStudentId6.Text); if (studyStudentId7.Text != "" && studyStudentId7.Enabled != false) doc.GetElementById("ctl00_ContentPlaceHolder_txtcompany_7").SetAttribute("value", studyStudentId7.Text); if (studyStudentId8.Text != "" && studyStudentId8.Enabled != false) doc.GetElementById("ctl00_ContentPlaceHolder_txtcompany_8").SetAttribute("value", studyStudentId8.Text); if (studyEtc.Text != "") doc.GetElementById("ctl00_ContentPlaceHolder_txtnote").SetAttribute("value", studyEtc.Text); HTMLDocument hdoc = doc.DomDocument as HTMLDocument; foreach (IHTMLElement hel in (IHTMLElementCollection)hdoc.body.all) { if (hel.getAttribute("id", 0) != null) { if (hel.getAttribute("id", 0).ToString().IndexOf("ctl00_ContentPlaceHolder_btnSubmit") != -1) { // 예약 완료 or 미완료 메세지 hel.click(); } } } while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } if (browser.Url.ToString().IndexOf("Detail.aspx") == -1) { MessageBox.Show("입력한 값에 오류가 있습니다 :&", "Robot의 경고"); } if (isLoading == true) return; studyDate.Text = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString(dateFormat); loadStudyRoomStat(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString(dateFormat)); }
private static double? SimpleMultiCalc(HtmlDocument doc, string fieldId) { double? nullable3; double num2; double? nullable = 0.0; int num = 1; string str = fieldId.Remove(fieldId.Length - 1); HtmlElement elementById = doc.GetElementById(str + "_" + num.ToString()); nullable = 0.0; if (elementById != null) { nullable = 1.0; do { try { double? nullable4; string str2 = elementById.GetAttribute("value").Trim(); LoggingService.DebugFormatted("{0}-{1}:{2}", new object[] { elementById.Id, elementById.GetAttribute("dbcolumn"), str2 }); if (elementById.GetAttribute("iskj") == "1") { if (!string.IsNullOrEmpty(str2)) { LoggingService.DebugFormatted("计算扣减额", new object[0]); nullable3 = nullable; num2 = double.Parse(str2); nullable = nullable3.HasValue ? new double?(nullable3.GetValueOrDefault() - num2) : ((double?) (nullable4 = null)); } } else { if ((str2 == null) || (str2.Length == 0)) { nullable = 0.0; break; } if (str2.EndsWith("%")) { nullable3 = nullable; nullable = nullable3.HasValue ? new double?(nullable3.GetValueOrDefault() / 100.0) : ((double?) (nullable4 = null)); str2 = str2.Remove(str2.Length - 1); } nullable3 = nullable; num2 = double.Parse(str2); nullable = nullable3.HasValue ? new double?(nullable3.GetValueOrDefault() * num2) : ((double?) (nullable4 = null)); } num++; elementById = doc.GetElementById(str + "_" + num.ToString()); } catch (Exception exception) { LoggingService.Error(exception); return null; } } while (elementById != null); } if ((doc.GetElementById(str + "_c") != null) && (doc.GetElementById(str + "_d") != null)) { string str3 = doc.GetElementById(str + "_c").GetAttribute("value").Trim(); string str4 = doc.GetElementById(str + "_d").GetAttribute("value").Trim(); if ((((str3 != null) && (str3.Length != 0)) && (str4 != null)) && (str4.Length != 0)) { nullable3 = nullable; num2 = double.Parse(doc.GetElementById(str + "_c").GetAttribute("value").Trim()) / double.Parse(doc.GetElementById(str + "_d").GetAttribute("value").Trim()); nullable = nullable3.HasValue ? new double?(nullable3.GetValueOrDefault() * num2) : null; } } LoggingService.DebugFormatted("{0}:{1}", new object[] { doc.GetElementById(fieldId).GetAttribute("dbcolumn"), nullable }); return nullable; }
private void button_GetData_Click(object sender, EventArgs e) { System.Windows.Forms.HtmlDocument mydoc = webBrowser1.Document; //gets the name of the linked in contact HtmlElement ename = mydoc.GetElementById("name"); HtmlElement eCompany = mydoc.GetElementById("title"); HtmlElement elocation = mydoc.GetElementById("location"); HtmlElement eposition = mydoc.GetElementById("background-experience-container"); //set strings from html document string name = ename.InnerText; string company = eCompany.InnerText; string location = elocation.OuterText; string URL = webBrowser1.Url.ToString(); //make the add to list button visible and hide get data button_GetData.Visible = false; button1.Visible = true; string sJobCompany = ""; if (eposition != null) { // Get the first h5 element HtmlElementCollection h5Collection = eposition.GetElementsByTagName("h5"); if (h5Collection != null) { switch (h5Collection.Count) { case 0: //show not found text and set textbox color to red sJobCompany = "No Company Found!"; textBox_CompanyName.BackColor = Color.IndianRed; break; case 1: sJobCompany = h5Collection[0].InnerText; break; case 2: sJobCompany = h5Collection[1].InnerText; break; default: if (h5Collection.Count > 2) { // Greater than two sJobCompany = h5Collection[1].InnerText; if (sJobCompany == null) { sJobCompany = "No Company Found!"; } } else { // negative //show not found text and set textbox color to red sJobCompany = "No Company Found!"; textBox_CompanyName.BackColor = Color.IndianRed; } break; } } else { //show not found text and set textbox color to red sJobCompany = "No Company Found!"; textBox_CompanyName.BackColor = Color.IndianRed; } } string slocation = ""; if (elocation != null) { if (elocation.GetElementsByTagName("dd") != null) { //get the first dd in location foreach (HtmlElement ddElement in elocation.GetElementsByTagName("dd")) { // Get the first dd element slocation = ddElement.InnerText; break; } } else { slocation = "BAD-DATA"; } } //do validation on the position string clean_current_company = ""; if (company != null) { //remove the words experience and current from text clean_current_company = company.Replace("Edit experienceCurrent", "").Trim(); } else { clean_current_company = "No Position Found"; textBox_Position.BackColor = Color.IndianRed; } //remove the words experience and current from text string clean_current_position = sJobCompany.Replace("Edit experienceCurrent", "").Trim(); // Newline separator string[] saSeparatorNewline = new string[1]; saSeparatorNewline[0] = "\r\n"; // Comma separator string[] saSeparatorComma = new string[1]; saSeparatorComma[0] = ","; // Space separator string[] saSeparatorSpace = new string[1]; saSeparatorSpace[0] = " "; // Truncate anything after first comma for postition string sCompanyCleanse = clean_current_company; textBox_Position.Text = sCompanyCleanse; // Truncate anything after first comma for postition string sPositionCleanse = clean_current_position.Split(saSeparatorComma, StringSplitOptions.RemoveEmptyEntries)[0].Trim(); textBox_CompanyName.Text = sPositionCleanse; //set strings to null so we can get the outside of loop string clean_state = ""; string sCity = ""; //check to see if data is bad from source if (slocation != "BAD-DATA") { //split on return new line string[] saLocationStrings = slocation.Split(saSeparatorNewline, StringSplitOptions.RemoveEmptyEntries); //do filter logic to seperate city and state and reject "area" foreach (string sLocation in saLocationStrings) { int iCommaLoc = sLocation.IndexOf(","); if (iCommaLoc > -1) { string[] saParts = sLocation.Split(','); if (saParts.Length >= 2) { // We know we have two part here that look like the city and state sCity = saParts[0]; textBox_City.Text = sCity; string sState = saParts[1]; clean_state = sState.Replace("Area", "").Trim(); textBox_State.Text = clean_state; } } } } else { clean_state = "No State Found!"; textBox_State.BackColor = Color.IndianRed; } //split on space detect // Truncate anything after first comma string sNameCleanse = name.Split(saSeparatorComma, StringSplitOptions.RemoveEmptyEntries)[0].Trim(); // Parse out name by spaces string[] saNameStrings = sNameCleanse.Split(saSeparatorSpace, StringSplitOptions.RemoveEmptyEntries); string sFirst_Name = ""; string sLast_Name = ""; if (saNameStrings != null) { // Declare Name sFirst_Name = ""; string sMiddle_Name = ""; sLast_Name = ""; switch (saNameStrings.Length) { case 0: sFirst_Name = ""; sMiddle_Name = ""; sLast_Name = ""; sFirst_Name = "Not Found"; textBox_FirstName.BackColor = Color.IndianRed; sLast_Name = "Not Found"; textBox_LastName.BackColor = Color.IndianRed; break; case 1: sFirst_Name = saNameStrings[0]; textBox_FirstName.Text = saNameStrings[0]; sMiddle_Name = ""; sLast_Name = ""; sLast_Name = "Not Found"; textBox_LastName.BackColor = Color.IndianRed; break; case 2: sFirst_Name = saNameStrings[0]; textBox_FirstName.Text = saNameStrings[0]; sMiddle_Name = ""; sLast_Name = saNameStrings[1]; textBox_LastName.Text = saNameStrings[1]; break; case 3: sFirst_Name = saNameStrings[0]; textBox_FirstName.Text = saNameStrings[0]; sMiddle_Name = saNameStrings[1]; sLast_Name = saNameStrings[2]; textBox_LastName.Text = saNameStrings[2]; break; default: if (saNameStrings.Length > 3) { sFirst_Name = saNameStrings[0]; textBox_FirstName.Text = saNameStrings[0]; sMiddle_Name = saNameStrings[1]; sLast_Name = saNameStrings[2]; textBox_LastName.Text = saNameStrings[2]; } else { sFirst_Name = ""; sMiddle_Name = ""; sLast_Name = ""; } break; } } else { sFirst_Name = "Not Found"; textBox_FirstName.BackColor = Color.IndianRed; sLast_Name = "Not Found"; textBox_LastName.BackColor = Color.IndianRed; } }
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (webBrowser1.ReadyState == WebBrowserReadyState.Complete) { html = webBrowser1.Document; HtmlElement img = html.GetElementById("CodeImg"); if (img == null) return; img.Style = "position:absolute;z-index:9999;top:0px;left:0px"; Bitmap b = new Bitmap(img.ClientRectangle.Width, img.ClientRectangle.Height); webBrowser1.DrawToBitmap(b, new Rectangle(new Point(), img.ClientRectangle.Size)); pictureBox1.Image = b; if (StateInfo.alart.Contains("密码")) { autoLogin = false; MessageBox.Show("密码错误", "提示"); checkBox2.Checked = false; StateInfo.alart = ""; button3_Click(sender, e); } else if (StateInfo.alart.Contains("验证码")) { autoLogin = false; MessageBox.Show("验证码错误", "提示"); checkBox2.Checked = false; StateInfo.alart = ""; button3_Click(sender, e); textBox1.Focus(); textBox1.Text = ""; } else if (StateInfo.alart == "click") { StateInfo.userID = comboBox1.Text; StateInfo.password = textBox2.Text; this.DialogResult = DialogResult.OK; this.Close(); } modifyConf(this.comboBox1.Text, this.textBox2.Text); } if (webBrowser1.ReadyState == WebBrowserReadyState.Interactive) { //MessageBox.Show(StateInfo.alart, "Int"); } }
private static double? QJCalc(HtmlDocument doc, string p) { string[] strArray = p.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); double? nullable = null; HtmlElement elementById = doc.GetElementById(strArray[0]); if (elementById != null) { double num; if (double.TryParse(elementById.GetAttribute("value"), out num)) { int length = strArray.Length; for (int i = 1; i < length; i++) { double num4; if (double.TryParse(strArray[i], out num4)) { if (length > (i + 1)) { if (num <= num4) { double num5; if (double.TryParse(strArray[i + 1], out num5)) { return new double?(num5); } LoggingService.WarnFormatted("{0} 不是数字", new object[] { strArray[i + 1] }); return nullable; } } else { nullable = new double?(num4); } } else { LoggingService.WarnFormatted("{0} 不是数字", new object[] { strArray[i] }); return nullable; } i++; } } return nullable; } LoggingService.WarnFormatted("找不到控件 {0} ", new object[] { strArray[0] }); return nullable; }
private void CopyUserInfo(string[] dknames, HtmlDocument doc, string newvalue) { foreach (string str in dknames) { HtmlElement elementById = doc.GetElementById(str); if (elementById != null) { string str2 = string.IsNullOrEmpty(elementById.GetAttribute("value")) ? newvalue : (elementById.GetAttribute("value") + @"\" + newvalue); this.SetTableRowValue(elementById.GetAttribute("dbtable"), elementById.GetAttribute("dbcolumn"), 0, str2, new GetTableRowValueString(this.GetHtmlElementValue), elementById); this.SetElseWebBrowseHtmlElementValue(doc, elementById.Id, str2); } else { LoggingService.WarnFormatted("找不到控件:{0}", new object[] { str }); } } }
private void button4_Click(object sender, EventArgs e) { try { document = webBrowser1.Document; formElement = document.GetElementById("form1"); form = (mshtml.HTMLFormElement)formElement.DomElement; deptElement = document.GetElementById("ddl_depart"); deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement); personElement = document.GetElementById("ddl_person"); personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement); btnElement = document.GetElementById("btn_Query"); btn = (mshtml.HTMLInputElement)(btnElement.DomElement); deptElement = document.GetElementById("ddl_depart"); deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement); formElement = document.GetElementById("form1"); form = (mshtml.HTMLFormElement)formElement.DomElement; deptSelector.selectedIndex = 0; deptSelector.FireEvent("onchange"); form.submit(); personElement = document.GetElementById("ddl_person"); personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement); personSelector.selectedIndex = 0; //Application.DoEvents(); } catch { } }
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")); } } }
private static void SetHtmlElementValue(HtmlDocument doc, DataSet ds, HtmlElement he, Dictionary<string, InvokeResult> invokes) { string attribute = he.GetAttribute("ref"); if ((attribute != null) && (attribute.Trim().Length > 0)) { HtmlElement elementById = doc.GetElementById(attribute); if (elementById != null) { double? nullable = HtmlElementCalc(doc, elementById, invokes); SetHtmlElementValue(he, nullable.HasValue ? MathHelper.Round(nullable.Value, 2).ToString("0.00") : string.Empty); } } else { string getdata = he.GetAttribute("getdata").Trim().Replace("\r", "").Replace("\n", ""); if ((getdata != null) && (getdata.Length > 0)) { SetHtmlElementValue(he, ParseGetData(doc, he.GetAttribute("dbcolumn"), ds, getdata, invokes)); } } }
public void FillWebPage(HtmlDocument document, bool submit) { // 网页中的提交按钮 HtmlElement inputSubmit = null; //设置html元素的值并保存。如果这个元素是提交按钮,则指定为输入提交。 foreach (HtmlInputElement input in this.InputElements) { HtmlElement element = document.GetElementById(input.ID); if (element == null) { continue; } if (input is HtmlSubmit) { inputSubmit = element; } else { input.SetValue(element); } } // 自动点击提交按钮 if (submit && inputSubmit != null) { inputSubmit.InvokeMember("click"); } }
private void button1_Click(object sender, EventArgs e) { ///导出过程中导出键不可用 this.button1.Enabled = false; ///导出过程中暂停键可用 this.button2.Enabled = true; ///导出过程中统计键不可用 this.button3.Enabled = false; this.button4.Enabled = false; ExtractPlaying = true; try { string currentPath = Application.StartupPath; string dataFile = currentPath + "\\contacts.db"; bool isExist = File.Exists(dataFile); dataFile = "Data Source='" + dataFile + "'"; SQLiteConnection conn = new SQLiteConnection(dataFile + ";Pooling=true;FailIfMissing=false"); conn.Open(); var command = new SQLiteCommand(conn); if (!isExist) { command.CommandText = @"CREATE TABLE [PERSON] ( [ID] varchar NOT NULL PRIMARY KEY, [NAME] varchar, [DEPARTMENT] varchar, [MOBILE_PHONE] varchar, [VIRTUAL_PHONE] varchar, [POSITION] varchar, [REGION] varchar, [OFFICE_PHONE] varchar, [INNER_PHONE] varchar, [PY] varchar, [CAR] varchar )"; command.ExecuteNonQuery(); } document = webBrowser1.Document; formElement = document.GetElementById("form1"); form = (mshtml.HTMLFormElement)formElement.DomElement; deptElement = document.GetElementById("ddl_depart"); deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement); personElement = document.GetElementById("ddl_person"); personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement); btnElement = document.GetElementById("btn_Query"); btn = (mshtml.HTMLInputElement)(btnElement.DomElement); deptStringList = deptElement.OuterText.Split(new char[] { '—', ' ' }) .Where(p => p != string.Empty).Select(p => p.Trim()).ToList(); List<string> lastPersonStringList = new List<string>(); int currentDeptIndex = deptSelector.selectedIndex; for (int i = (currentDeptIndex == 0 ? currentDeptIndex : currentDeptIndex - 1); i < deptStringList.Count; i++) { bool IFailed = true; int IFailedCount = 0; while (IFailed && ExtractPlaying) { try { if (WinFormClose) { break; } bool LoadSuccess = true; deptElement = document.GetElementById("ddl_depart"); deptSelector = (mshtml.HTMLSelectElement)(deptElement.DomElement); formElement = document.GetElementById("form1"); form = (mshtml.HTMLFormElement)formElement.DomElement; deptSelector.selectedIndex = i + 1; deptSelector.FireEvent("onchange"); form.submit(); System.Threading.Thread.Sleep(500); Application.DoEvents(); personElement = document.GetElementById("ddl_person"); personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement); var tempPersonStringList = personElement.OuterText.Split(new char[] { '—', ' ' }) .Where(p => p != string.Empty).Select(p => p.Trim()).ToList(); personStringList = new List<string>(); //get current dept persons for (int j = 0; j < tempPersonStringList.Count; j++) { if (j % 2 == 1) personStringList.Add(tempPersonStringList[j]); } if (lastPersonStringList.Count == personStringList.Count) { if (lastPersonStringList.Count > 0) { if (lastPersonStringList[0] == personStringList[0]) { LoadSuccess = false; } else { lastPersonStringList.Clear(); foreach (string oneName in personStringList) { lastPersonStringList.Add(oneName); } } } else { if (IFailedCount < 5) { LoadSuccess = false; IFailedCount++; } else if (lastPersonStringList.Count == 0) { IFailed = false; } } } else { lastPersonStringList.Clear(); foreach (string oneName in personStringList) { lastPersonStringList.Add(oneName); } } if (LoadSuccess) { int currentPersonIndex = personSelector.selectedIndex; for (int j = (currentPersonIndex == 0 ? currentPersonIndex : currentPersonIndex - 1); j < personStringList.Count; j++) { bool JFailed = true; int JFailedCount = 0; while (JFailed && ExtractPlaying) { try { personElement = document.GetElementById("ddl_person"); personSelector = (mshtml.HTMLSelectElement)(personElement.DomElement); personSelector.selectedIndex = j + 1; //personSelector.FireEvent("onchange"); //记录下拉框的工号,用于对比判断下面信息是否刷新 string CurrentSelectedID = personSelector.value; btnElement = document.GetElementById("btn_Query"); btn = (mshtml.HTMLInputElement)(btnElement.DomElement); btn.click(); System.Threading.Thread.Sleep(200); Application.DoEvents(); formElement = document.GetElementById("form1"); form = (mshtml.HTMLFormElement)formElement.DomElement; var tableElement = formElement.GetElementsByTagName("table")[1]; var table = (mshtml.HTMLTable)tableElement.DomElement; var cells = table.cells.Cast<mshtml.HTMLTableCell>().ToList(); string id = cells[1].innerText.Trim(); if (CurrentSelectedID == id) { string name = cells[3].innerText.Trim(); string dept = cells[5].innerText.Trim(); string mobile = cells[7].innerText.Trim(); string virt = cells[9].innerText.Trim(); string position = cells[11].innerText.Trim(); string region = cells[13].innerText.Trim(new char[] { '区', '号', ' ' }); string office = cells[14].innerText.Trim(new char[] { '电', '话', ' ' }); string inner = cells[15].innerText.Trim(new char[] { '分', '机', ' ' }); string car = cells[17].innerText.Trim(); command.CommandText = "select count(*) from [PERSON] where [ID]='" + id + "'"; var result = int.Parse(command.ExecuteScalar().ToString()); if (result == 0) { command.CommandText = string.Format(@"INSERT INTO [PERSON] ([ID] ,[NAME] ,[DEPARTMENT] ,[MOBILE_PHONE] ,[VIRTUAL_PHONE] ,[POSITION] ,[REGION] ,[OFFICE_PHONE] ,[INNER_PHONE] ,[PY] ,[CAR]) VALUES ('{0}' ,'{1}' ,'{2}' ,'{3}' ,'{4}' ,'{5}' ,'{6}' ,'{7}' ,'{8}' ,'{9}' ,'{10}')", id, name, dept, mobile, virt, position, region, office, inner, ConvertHZToPY.ToChineseSpell(name), car); command.ExecuteNonQuery(); } else if (result > 0) { command.CommandText = string.Format(@"UPDATE [PERSON] SET [ID] = '{0}' ,[NAME] = '{1}' ,[DEPARTMENT] ='{2}' ,[MOBILE_PHONE] = '{3}' ,[VIRTUAL_PHONE] ='{4}' ,[POSITION] = '{5}' ,[REGION] ='{6}' ,[OFFICE_PHONE] ='{7}' ,[INNER_PHONE] = '{8}' ,[PY]='{9}' ,[CAR]='{11}' WHERE [ID]='{10}'", id, name, dept, mobile, virt, position, region, office, inner, ConvertHZToPY.ToChineseSpell(name), id, car); command.ExecuteNonQuery(); } JFailed = false; } else { //如果下拉框和下面信息不一致,本次信息抓取失败,重新抓取 JFailed = true; JFailedCount++; } } catch (Exception ex) { Trace.TraceError(ex.Message); JFailedCount++; if (JFailedCount > 5) { System.Threading.Thread.Sleep(JFailedCount * 200); Application.DoEvents(); } } } } IFailed = false; } } catch (Exception ex) { Trace.TraceError(ex.Message); IFailedCount++; if (IFailedCount > 5) { System.Threading.Thread.Sleep(IFailedCount * 200); Application.DoEvents(); } } } } conn.Close(); } catch { MessageBox.Show("认证失败,请重新打开本软件"); } ///导出结束后导出键可用 this.button1.Enabled = true; ///导出结束后暂停键不可用 this.button2.Enabled = false; ///导出结束中统计键可用 this.button3.Enabled = true; this.button4.Enabled = true; ExtractPlaying = false; MessageBox.Show("导出结束!"); if (WinFormClose) { this.Close(); } }