예제 #1
1
파일: Index.cs 프로젝트: ngprice/wcscrape
        private Series ParseSeries(HtmlDocument doc)
        {
            var result = new Series();
            result.Title = Find(FindTitle, doc);
            result.Description = Find(FindDescription, doc);

            return result;
        }
예제 #2
0
        public static bool LoadJsFile(HtmlDocument doc, string js)
        {
            bool noErr = true;
            string file = String.Empty;
            try
            {
                string[] files = js.Split(new char[] { ',' });
                foreach (string f in files)
                {
                    file = GlobalVar.AppPath + "res\\" + f + ".js";

                    string s = Utility.ReadFile(file);
                    noErr &= !String.IsNullOrEmpty(s);

                    if(String.IsNullOrEmpty(s))
                        GlobalVar.Log.LogError("取得文件内空为空!",file);

                    ExecScript(doc, s);

                }
                doc.Write("<script language='javascript'>alert('hello');</script>");

            }

            catch (System.Exception )
            {
                MessageBox.Show("load [" + file + "] error");
                return false;
            }
            return noErr;
        }
예제 #3
0
 public DownloadInfo(Uri projectUrl, Uri articleUrl, HtmlDocument htmlDocument)
 {
     m_projectUrl = projectUrl;
     m_articleUrl = articleUrl;
     m_htmlDocument = htmlDocument;
     ParseCookies(htmlDocument.Cookie);
 }
예제 #4
0
        /// <summary>
        /// Get html element by foreach search the document
        /// </summary>
        /// <param name="document">html document which you want get element from </param>
        /// <param name="strElementId">element Id</param>
        /// <param name="strElementTagName">element tag name which you want</param>
        /// <param name="strAttribute">element attribute which you want</param>
        /// <param name="strBtnName">element inner text</param>
        /// <returns>html element</returns>
        private HtmlElement GetHtmlElement(System.Windows.Forms.HtmlDocument document, string strElementId, string strElementTagName, string strAttribute, string strBtnName)
        {
            //statment the return object
            HtmlElement returnBtnObj         = null;
            var         htmlNewOfflineDialog = document.All[strElementId];

            if (htmlNewOfflineDialog != null)
            {
                if (string.IsNullOrEmpty(strAttribute))
                {
                    returnBtnObj = htmlNewOfflineDialog.GetElementsByTagName(strElementTagName)[0];
                }
                else
                {
                    //Find out the object equals that the attribute of strAttribute is strBtnName
                    foreach (System.Windows.Forms.HtmlElement temp in htmlNewOfflineDialog.GetElementsByTagName(strElementTagName))
                    {
                        if (temp.GetAttribute(strAttribute) == strBtnName)
                        {
                            returnBtnObj = temp;
                        }
                    }
                }
            }
            if (returnBtnObj != null)
            {
                return(returnBtnObj);
            }
            else
            {
                return(null);
            }
        }
예제 #5
0
        //Change the directory to the selected directory
        private void timChangeDir_Tick(object sender, EventArgs e)
        {
            //Stop the timer to finish the change directory process.
            timChangeDir.Stop();

            System.Windows.Forms.HtmlDocument document = this.webBrowser1.Document;

            //Get the directory list htmlElement.
            var htmlDirList = GetHtmlElement(webBrowser1.Document, "fileTreeDialog", "SPAN", "InnerText", "全部文件").Parent.Parent.NextSibling;

            //Search the selected directory
            foreach (HtmlElement htmlnode in htmlDirList.GetElementsByTagName("SPAN"))
            {
                if (htmlnode.InnerText == trvFileTreeOfBaiduPan.SelectedNode.Text)
                {
                    //check the directory
                    htmlnode.InvokeMember("click");

                    //press the confirm button
                    htmlDirList.Parent.Parent.Parent.Parent.NextSibling.FirstChild.NextSibling.FirstChild.InvokeMember("click");
                    break;
                }
            }

            timChangDirDownload.Interval = (int)npdDelayTime.Value;
            timChangDirDownload.Start();
        }
예제 #6
0
        private static XmlDocument DOMTreeToXml(HtmlDocument htmlDoc)
        {
            XmlDocument result = new XmlDocument();
            if(htmlDoc != null &&
               htmlDoc.Body != null &&
               htmlDoc.Body.Parent != null)
            {
              	    HtmlElement topHtml = htmlDoc.Body.Parent;
              	    using (StringReader sReader = new StringReader(topHtml.OuterHtml))
              	    {
              	      using (StringWriter errorLog = new StringWriter())
              	      {
              	        Sgml.SgmlReader reader = new Sgml.SgmlReader();
              	        reader.ErrorLog = errorLog;
              	        reader.InputStream = sReader;
              	        using (StringReader dtdReader = new StringReader(Properties.Resources.WeakHtml))
              	          reader.Dtd = Sgml.SgmlDtd.Parse(null, "HTML", null, dtdReader, null, null, reader.NameTable);

              	        result.Load(reader);
              	        errorLog.Flush();
              	        Console.WriteLine(errorLog.ToString());
              	      }
              	    }
            }
              	  return result;
        }
예제 #7
0
        /// <summary>
        /// The timer that begin load TreeViewList datas
        /// </summary>
        private void timLoadFileTree_Tick(object sender, EventArgs e)
        {
            timLoadFileTree.Stop();
            System.Windows.Forms.HtmlDocument document = this.webBrowser1.Document;
            var         htmlFileTree = document.All["fileTreeDialog"];
            HtmlElement htmlHome     = htmlFileTree.GetElementsByTagName("LI")[0];

            string[] strSplit    = { "\r\n" };
            string[] strFileList = htmlHome.OuterText.Split(strSplit, StringSplitOptions.RemoveEmptyEntries);
            //foreach (HtmlElement htmltemp in htmlFileTree.GetElementsByTagName("LI"))
            //{
            //    htmltemp.GetElementsByTagName("LI");
            //}
            TreeNode tn = trvFileTreeOfBaiduPan.Nodes.Add(strFileList[0]);

            for (int i = 1; i < strFileList.Length - 1; i++)
            {
                if (strFileList[i] == "百度云收藏")
                {
                    tn.Nodes.Add("我的收藏");
                    continue;
                }
                tn.Nodes.Add(strFileList[i]);
            }
            trvFileTreeOfBaiduPan.ExpandAll();
        }
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.AbsolutePath.Contains("makers"))
            {
                StringBuilder sb = new StringBuilder();
                foreach (HtmlElement elm in webBrowser1.Document.All)
                {
                    if (elm.GetAttribute("className") == "main main-makers l-box col float-right")
                    {
                        sb.Append(elm.InnerHtml);
                    }
                }
                System.Windows.Forms.HtmlDocument doc = webBrowser1.Document;
                doc.Body.InnerHtml = sb.ToString();
            }
            else if (e.Url.AbsolutePath.Contains("phones"))
            {
                StringBuilder sbb = new StringBuilder();
                foreach (HtmlElement elm in webBrowser1.Document.All)
                {
                    if (elm.GetAttribute("className") == "makers")
                    {
                        sbb.Append(elm.InnerHtml);
                    }
                }
                System.Windows.Forms.HtmlDocument docc = webBrowser1.Document;
                docc.Body.InnerHtml = sbb.ToString();
            }

            if (splashScreenManager1.IsSplashFormVisible)
            {
                splashScreenManager1.CloseWaitForm();
            }
        }
예제 #9
0
        private void webBr_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            System.Windows.Forms.HtmlDocument document = webBr.Document;
            //htmlAgilityPack扩展库
            HtmlAgilityPack.HtmlDocument agHtmlDocument = new HtmlAgilityPack.HtmlDocument();
            agHtmlDocument.LoadHtml(webBr.DocumentText);
            HtmlNodeCollection htmlNodeName = agHtmlDocument.DocumentNode.SelectNodes("//div[@data-id]//a[@title]");
            HtmlNodeCollection htmlNodePhone = agHtmlDocument.DocumentNode.SelectNodes("//div[@data-id]/div[last()]/div[last()-1]/div[last()-1]//span[@class='sec-c3']");///div//span[@class='sec-c3']//following-sibling::span[1]
            List<String> dataId = new List<string>();
            foreach (HtmlNode item in htmlNodePhone)
            {
                String a = item.InnerHtml;

            }


            //if (webBr.Document.GetElementById("home-main-search") == null)
            //{
            //    return;
            //}
            //webBr.Document.GetElementById("home-main-search").InnerText = "百度";
            //Thread.Sleep(2000);
            ////调用js函数
            //webBr.Document.InvokeScript("header.search(true,'#home-main-search') ");

        }
 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 });
                 }
             }
         }
     }
 }
예제 #11
0
        public Download(HtmlDocument document, string key, string url, string filename)
        {
            this.url = url;
            this.key = key;
            this.document = document;
            target = Path.Combine(Path.GetTempPath(), filename);
            if (File.Exists(target))
                status = DownloadStatus.DOWNLOADED;
            else
                status = DownloadStatus.AVAILABLE;

            downloadBGWorker = new BackgroundWorker()
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };

            downloadBGWorker.DoWork += RunDownload;
            downloadBGWorker.ProgressChanged += UpdateProgress;
            downloadBGWorker.RunWorkerCompleted += DownloadFinished;

            extractBGWorker = new BackgroundWorker();

            extractBGWorker.DoWork += DoExtraction;
            extractBGWorker.RunWorkerCompleted += ExtractionFinished;
        }
 public WebBrowserHtmlCatalog(System.Windows.Forms.HtmlDocument doc, params Tuple <string, string>[] fragmentAndKeys)
 {
     this.doc = doc;
     foreach (var fragmentAndKey in fragmentAndKeys)
     {
         AddFragmentWithKey(fragmentAndKey.Item1, fragmentAndKey.Item2);
     }
 }
예제 #13
0
        public static HtmlDocumentHandle GetOrCreateDocumentHandle(HtmlDocument htmlDocument)
        {
            var guidObj = htmlDocument.InvokeScript (c_getDocumentIdentification);

              var docID = guidObj != null ? new HtmlDocumentHandle (Guid.Parse (guidObj.ToString())) : new HtmlDocumentHandle (Guid.NewGuid());

              htmlDocument.InvokeScript (c_addDocumentIdentification, new object[] { docID.ToString() });
              return docID;
        }
예제 #14
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");
        }
예제 #15
0
파일: Index.cs 프로젝트: ngprice/wcscrape
        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;
        }
예제 #16
0
        public void setScrollBar(int page)
        {
            System.Windows.Forms.HtmlDocument htmlDoc = webBrowser1.Document;

            if (page > 0)
            {
                htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop = Convert.ToInt32(page);
            }
        }
        /// <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);
        }
예제 #18
0
 private void Form4_Load(object sender, EventArgs e)
 {
     System.Windows.Forms.HtmlDocument document = this.webBrowser.Document;  // 자바스크립트 개객기
     //InternetExplorer ex = new InternetExplorer();
     //ex.Visible = true;
     //ex.Navigate("ani.today");
     this.TopMost = true;
     //webBrowser1.Navigate("moeni.net");
 }
예제 #19
0
        public static IBoodProduct Create(HtmlDocument doc)
        {
            try {
                var all = doc.All.Cast<HtmlElement>();
                var imgs = doc.Images.Cast<HtmlElement>();

                var img = GetElement(all, "IMG", "className", "main-prod-img") ?? imgs.FirstOrDefault(i => i.OuterHtml.Contains("class=main-prod-img"));

                var prodName = string.Empty;
                var prodImage = string.Empty;
                if (img != null) {
                    prodName = img.GetAttribute("alt");
                    prodImage = img.GetAttribute("src");
                }

                var spanOldPrice = GetElement(all, "SPAN", "className", "old-price");
                decimal oldPrice = 0;
                try {
                    oldPrice = decimal.Parse(spanOldPrice.InnerText, System.Globalization.NumberStyles.Currency);
                }
                catch { }

                var spanOurPrice = GetElement(all, "P", "className", "our-price");
                decimal ourPrice = 0;
                decimal shippingCost = 0;
                try {
                    // "iBOOD PrijsNu! € 149,95 + (8,95) "
                    var priceParts = spanOurPrice.InnerText.Split(new char[] {'€', ' ', '+', '(' ,')'}, StringSplitOptions.RemoveEmptyEntries );
                    shippingCost   = decimal.Parse(priceParts[2]);
                    ourPrice = decimal.Parse(priceParts[3]); //decimal.Parse(spanOurPrice.InnerText, System.Globalization.NumberStyles.Currency);
                }
                catch { }

                var divIsSoldOut = GetElement(all, "DIV", "id", "issoldout");
                var isSoldOut = divIsSoldOut != null && divIsSoldOut.Style.ToLower() == "display:none";

                var aMoreInfo = GetElement(all, "A", "id", "speclink");
                var moreInfoUri = aMoreInfo.GetAttribute("href");

                var aBuyNow = GetElement(all, "A", "id", "btnbuy");
                var buyNowUri = aBuyNow.GetAttribute("href");

                return new IBoodProduct {
                    Name = prodName,
                    ImageUri = new Uri(prodImage),
                    Status = isSoldOut ? ProductStatus.IsSoldOut : ProductStatus.NotSoldOut,
                    RegularPrice = oldPrice,
                    OurPrice= ourPrice ,
                    ShippingCost = shippingCost,
                    MoreInfoUri = new Uri(moreInfoUri),
                    BuyNowUri = new Uri(buyNowUri)
                };
            }
            catch { }
            return null;
        }
예제 #20
0
        public HtmlDocumentAdapter( HtmlDocument doc )
        {
            if ( doc == null )
            {
                throw new ArgumentNullException( "doc" );
            }

            Document = doc;
            myElementAdapters = new Dictionary<HtmlElement, HtmlElementAdapter>();
        }
예제 #21
0
        public bookForm(string user_id, string book_id, int page_number, string title)
        {
            this.user_id     = user_id;
            this.book_id     = book_id;
            this.page_number = page_number;
            this.title       = title;
            this.htmlDoc     = htmlDoc;

            InitializeComponent();
        }
예제 #22
0
 private IEnumerable <HtmlElement> ElementsByClass(System.Windows.Forms.HtmlDocument doc, string className)
 {
     foreach (HtmlElement e in doc.All)
     {
         if (e.GetAttribute("className") == className)
         {
             yield return(e);
         }
     }
 }
예제 #23
0
        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();
        }
예제 #24
0
        //Login button Click event
        private void btnLogin_Click(object sender, EventArgs e)
        {
            //Judge the state of the web is logined or not.
            if (btnLogin.Text == "退出")
            {
                npdDelayTime.Enabled       = false;
                ckbIsChangeDir.Enabled     = false;
                btnOfflineDownFile.Enabled = false;
                btnLogin.Text = "登录";
                //webBrowser1.Dispose();
                WebBrowser webNewBrowser = new WebBrowser();
                webBrowser1.Dispose();
                webBrowser1 = webNewBrowser;
                webBrowser1.Navigate("https://passport.baidu.com/v2/?login");
                webBrowser1.Visible = true;
                panViewWindow.Controls.Add(webBrowser1);
                panViewWindow.Controls[0].Dock = DockStyle.Fill;
                panViewWindow.Visible          = false;
                webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
                lblErrorMsg.Text = "";
                webBrowser1.ScriptErrorsSuppressed = true;
                return;
            }

            //Set the webBrowser1 do not show the alert dialog.
            this.webBrowser1.ScriptErrorsSuppressed = true;

            //If the user didn't login the BaiduPan,begin load the username and password and login.
            if (string.IsNullOrEmpty(txbUserName.Text) && string.IsNullOrEmpty(txbPassWord.Text))
            {
                lblErrorMsg.Text = "用户名或者密码不能为空,请输入!";
                return;
            }
            string strUserName = txbUserName.Text;
            string strPsw      = txbPassWord.Text;

            System.Windows.Forms.HtmlDocument document = this.webBrowser1.Document;
            if (document == null)
            {
                return;
            }
            document.All["TANGRAM__PSP_3__userName"].SetAttribute("Value", strUserName); //用户名
            document.All["TANGRAM__PSP_3__password"].SetAttribute("Value", strPsw);      //密码
            if (document.All["TANGRAM__PSP_3__memberPass"].GetAttribute("CHECKED") == "True")
            {
                document.All["TANGRAM__PSP_3__memberPass"].InvokeMember("click"); //是否自动登录
            }
            document.All["TANGRAM__PSP_3__submit"].InvokeMember("click");         //登录按钮的click方法
            //上面显示登录成功的界面,下面进行跳转,就没有用户了。

            Thread.Sleep(1000);//重点(需要引用using System.Threading;)

            this.webBrowser1.Navigate("http://pan.baidu.com/");
        }
예제 #25
0
        public WebEngine(HtmlDocument document, string webRoot)
        {
            _document = document;
            _webRoot = webRoot;

            session = engine.CreateSession(document);
            session.AddReference("System.Windows.Forms");

            RegisterEvents();
            CompileScripts();
        }
예제 #26
0
        public Int16 SetValuesToHTML(System.Windows.Forms.HtmlDocument document, ref Int32[] ValuesOfSource)
        {
            Object[] objArray = new Object[10];
            for (int i = 0; i < 10; i++)
            {
                objArray[i] = (Object)(ValuesOfSource[i]);
            }

            document.InvokeScript("SetValuesToHTML", objArray);
            return(0);
        }
예제 #27
0
        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}");
        }
예제 #28
0
        /// <summary>
        /// This method performs the auto sign-on by populating the given credentials
        /// in their corresponding credential fields and submitting the page.
        /// </summary>
        /// <param name="application">
        /// The credentials of the user to be populating in the credential fields identified.
        /// </param>
        public void DoLogin(object application)
        {
            HostedWebApplication app = (HostedWebApplication)application;

            webBrowser = (System.Windows.Forms.WebBrowser)app.TopLevelWindow;
            System.Windows.Forms.HtmlDocument axDoc = webBrowser.Document;

            if (null == app.LoginFields || app.LoginFields.Count == 0 || axDoc == null)
            {
                return;
            }

            int setFieldCount = 0;

            // For each credential field, perform the required operation.
            foreach (LoginFieldRecord field in app.LoginFields)
            {
                HtmlElement element;

                int sequence = (null != field.ControlSequence && string.Empty != field.ControlSequence ? int.Parse(field.ControlSequence) : -1);

                // Get the reference to the element corresonding to the credential field.
                //element = GetElement(axDoc, field.AttributeIdentity, field.AttributeValue, sequence);
                // TODO Update GetElement function to work with new WebBrowser
                // for first pass go with ID
                element = webBrowser.Document.GetElementById(field.AttributeValue);

                // If element is not found, then auto sign-on is failed, stop the auto sign-on
                if (null == element)
                {
                    throw new LoginFieldNotFoundException(field.LabelName);
                }

                switch (field.Operation)
                {
                // Populate the credentials in the value attribute of the element.
                case SET_OPERATION:
                {
                    Set(element, app.AgentCreds[setFieldCount]);
                    setFieldCount++;
                    break;
                }

                // Perform click operation on the element.
                case CLICK_OPERATION:
                {
                    Click(element);
                    break;
                }
                }
            }
        }
예제 #29
0
 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;
 }
예제 #30
0
        public static object ExecScript(HtmlDocument doc, string js)
        {
            object ret = null;
            if (String.IsNullOrEmpty(js) == false)
            {
                mshtml.IHTMLDocument2 d = doc.DomDocument as mshtml.IHTMLDocument2;
                mshtml.IHTMLWindow2 win = d.parentWindow as mshtml.IHTMLWindow2;
                ret = win.execScript(js, "javascript");

            }

            return ret;
        }
예제 #31
0
        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);
        }
예제 #32
0
        private void BodyLoaded(HtmlDocument doc)
        {
            outputSheet = new OutputSheet(doc);
            interpreter = new Interpreter(outputSheet);

            input.KeyPress += (sender, e) => {
                if (e.KeyChar == 13) {
                    OnEnter();
                    e.Handled = true;
                }
            };

            input.Focus();
        }
예제 #33
0
        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;
            }
        }
예제 #34
0
        /// <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);
        }
예제 #35
0
        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);
            }
        }
예제 #36
0
        private static string GetFaviconUrl(HtmlDocument document)
        {
            if (document == null)
                throw new NullReferenceException("Document should not be null!");

            if (document.Body == null)
                return GetDefaultFavicon(document.Url);

            var regex = new Regex("<link\\s+rel=\"shortcut icon\"\\s+href=\"(.+)\">");
            var matches = regex.Match(document.Body.InnerHtml);
            if (matches.Length == 0 || matches.Captures.Count < 1)
                return GetDefaultFavicon(document.Url);

            return matches.Captures[1].Value;
        }
예제 #37
0
        //If the timOffileDown ticked,find the 新建链接任务 button and click it
        //then start the timDown timer
        private void timer1_Tick(object sender, EventArgs e)
        {
            timOffileDown.Stop();

            System.Windows.Forms.HtmlDocument document = this.webBrowser1.Document;
            var htmlNewLinDown = document.All["_disk_id_2"];

            if (htmlNewLinDown != null)
            {
                htmlNewLinDown.InvokeMember("click");
            }
            //timOffileDown.Stop();
            timDown.Interval = (int)npdDelayTime.Value;
            timDown.Start();
        }
예제 #38
0
        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);
        }
예제 #39
0
        private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.ToString().Contains("/Success?"))
            {
                System.Windows.Forms.HtmlDocument document = this.wb.Document;

                string em = document.All["user_email"].GetAttribute("value");
                string pw = document.All["user_password"].GetAttribute("value");

                vu = new Models.LoginModels.ValidUser();
                vu.LoginUserName     = em;
                vu.LoginUserPassword = pw;

                this.Close();
            }
        }
예제 #40
0
        /// <summary>
        /// 得到验证码图片
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="ImgName"></param>
        /// <returns></returns>
        public static Image GetPic(HtmlDocument doc, string ImgName)
        {
            Image RegImg;
            HTMLDocument domDoc = (HTMLDocument)doc.DomDocument;

            HTMLBody body = (HTMLBody)domDoc.body;
            IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();
            IHTMLControlElement Img;

            Img = (IHTMLControlElement)doc.All[ImgName].DomElement;

            rang.add(Img);
            rang.execCommand("Copy", false, null);
            RegImg = Clipboard.GetImage();
            Clipboard.Clear(); return RegImg;
        }
예제 #41
0
    private void webBrowser1_Navigating(object sender,
                                        WebBrowserNavigatingEventArgs e)
    {
        System.Windows.Forms.HtmlDocument document =
            this.webBrowser1.Document;

        if (document != null && document.All["userName"] != null &&
            String.IsNullOrEmpty(
                document.All["userName"].GetAttribute("value")))
        {
            e.Cancel = true;
            System.Windows.Forms.MessageBox.Show(
                "You must enter your name before you can navigate to " +
                e.Url.ToString());
        }
    }
예제 #42
0
        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 WebBrowserHtmlCatalog(System.Windows.Forms.HtmlDocument doc, params string[] fragments)
 {
     foreach (var fragment in fragments)
     {
         var container = doc.CreateElement("div");
         container.InnerHtml = fragment;
         var root    = container.Children[0];
         var exports = root.Children.OfType <System.Windows.Forms.HtmlElement>().Where(e => !String.IsNullOrEmpty(e.GetAttribute(exportAttributeName)));
         if (exports.Any())
         {
             foreach (var export in exports)
             {
                 htmlParts.Add(new HTMLComposablePartDefinition(export));
             }
         }
     }
 }
  /// <devdoc> AddDocumentShim - adds a HtmlDocumentShim to list of shims to manage 
  ///   Can create a WindowShim as a side effect so it knows when to self prune from the list.
  ///</devdoc>
  public void AddDocumentShim(HtmlDocument doc) {
     HtmlDocument.HtmlDocumentShim shim = null;
     
     if (htmlDocumentShims == null) {
         htmlDocumentShims = new Dictionary<HtmlDocument,HtmlDocument.HtmlDocumentShim>();
         shim = new HtmlDocument.HtmlDocumentShim(doc);
         htmlDocumentShims[doc] = shim;
     }
     else if (!htmlDocumentShims.ContainsKey(doc)) {
         shim = new HtmlDocument.HtmlDocumentShim(doc);
         htmlDocumentShims[doc] = shim;
     }
     if (shim != null) {
         OnShimAdded(shim);
     }
     
 }
예제 #45
0
        private void GotoEarningsCalendar()
        {
            doc = webBrowser1.Document;

            HtmlElementCollection oHtmlElements = doc.Links;
            foreach (HtmlElement eLink in oHtmlElements)
            {
                if (eLink.GetAttribute("href").Length > 0)
                {
                    Console.WriteLine(eLink.Name);
                    Console.WriteLine(eLink.GetAttribute("href").ToString());
                }

                if (eLink.GetAttribute("href").IndexOf("earnings.aspx") > 0)
                    eLink.InvokeMember("Click");
            }
        }
예제 #46
0
        private void ActionsBuilderWebView_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // Set common properties (name, is scene or object, etc.)
            _document = ActionsBuilderWebView.Document;

            // Update screen
            _document.InvokeScript("hideButtons");

            // Set object name
            _document.GetElementById("ActionsBuilderObjectName").SetAttribute("value", _objectName);
            _document.InvokeScript("updateObjectName");

            if (isRootNode)
                _document.InvokeScript("setIsScene");
            else
                _document.InvokeScript("setIsObject");

            //_document.InvokeScript("updateObjectName");

            if (getProperty())
            {
                _document.GetElementById("ActionsBuilderJSON").SetAttribute("value", _jsonResult);
                _document.InvokeScript("loadFromJSON");
            }

            // 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");

            // Finish
            _document.InvokeScript("resetList");

            // Need to subclass this, then allow 3ds Max usage 
            //Win32.SubClass(this.ActionsBuilderWebView.Handle);
        }
예제 #47
0
        public void getCourceMenu(string url)
        {
            System.Windows.Forms.HtmlDocument doc = null; // HtmlDocument 오브젝트

            //for (int i = 198; i <= 210; i++)
            //{
            //string url = "http://www.facebook.com";

            browser.Navigate(url); // 이동
                                   //var webGet = new Htmlweb();

            while (browser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents(); // 웹페이지 로딩이 완료될 때 까지 대기
            }
            Stopwatch sw   = new Stopwatch();
            bool      flag = false;
            int       cnt  = 0;

            while (true)
            {
                Application.DoEvents();
                if (flag == false)
                {
                    sw.Start();
                    flag = true;
                }
                if (sw.ElapsedMilliseconds > 2000)
                {
                    textBox2.Text = sw.ElapsedMilliseconds.ToString() + " : " + cnt.ToString();
                    ScrollToBottom();
                    sw.Stop();
                    sw.Reset();
                    flag = false;
                    if (++cnt > 10)
                    {
                        break;
                    }
                }
            }
            doc = browser.Document as System.Windows.Forms.HtmlDocument;
            //HtmlElementCollection options = doc.GetElementsByTagName("title");

            //}
        }
예제 #48
0
        /// <summary>
        /// Click the "离线下载" button of the web
        /// </summary>
        /// <param name="document">current web document</param>
        private static void ClickOfflineDown(System.Windows.Forms.HtmlDocument document)
        {
            var         temp3         = document.All["layoutMain"];
            var         tempa         = temp3.FirstChild.GetElementsByTagName("a");
            HtmlElement heOfflineLink = null;

            foreach (System.Windows.Forms.HtmlElement temp in tempa)
            {
                if (temp.InnerText == "离线下载")
                {
                    heOfflineLink = temp;
                }
            }
            if (heOfflineLink != null)
            {
                heOfflineLink.InvokeMember("click");
            }
        }
예제 #49
0
 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;
     }
 }
예제 #50
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            resultbox.Text      = null;
            ishodopis.Text      = null;
            checkBox1.Checked   = false;
            checkBox2.Checked   = false;
            Marketbox.Checked   = false;
            Sitebox.Checked     = false;
            checkBox1.Enabled   = true;
            checkBox2.Enabled   = true;
            Marketbox.Enabled   = true;
            Sitebox.Enabled     = true;
            webBrowser1.Visible = false;
            HtmlDocument doc = webBrowser1.Document;

            doc.Body.InnerHtml = null;
            System.Windows.Forms.Application.DoEvents();
        }
예제 #51
0
 private void checkBox1_CheckedChanged(object sender, EventArgs e)
 {
     if (checkBox1.Checked == false)
     {
         checkBox2.Enabled   = true;
         webBrowser1.Visible = false;
         HtmlDocument doc = webBrowser1.Document;
         doc.Body.InnerHtml = null;
         System.Windows.Forms.Application.DoEvents();
     }
     else
     {
         checkBox2.Enabled   = false;
         webBrowser1.Visible = true;
         HtmlDocument doc = webBrowser1.Document;
         doc.Body.InnerHtml = ishodopis.Text;
     }
 }
예제 #52
0
 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;
         }
     }
 }
        private static bool HtmlDocEquals(HtmlDocument doc1, HtmlDocument doc2)
        {
            //return HtmlDocument.Equals(doc1, doc2);
              if (doc1 != null)
              {
            if (doc2 != null)
            {
              //Hack
              return doc1.Body == doc2.Body;
              //return doc1.All.Count == doc2.All.Count;

              //return doc1.Body.OuterHtml == doc2.Body.OuterHtml;
            }
            else
              return false;
              }
              else
            return doc2 == null;
        }
예제 #54
0
파일: Form1.cs 프로젝트: moonmile/etc
        /// <summary>
        /// 自分のツイートを取得する
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public List<Tweet> getTweets( HtmlDocument doc )
        {
            List<Tweet> items = new List<Tweet>();

            Tweet tw = null;
            bool skip = false;
            foreach (HtmlElement el in doc.All)
            {
                string cname = el.GetAttribute("className");
                if ( 	cname == "tweet-screen-name user-profile-link js-action-profile-name" ) {
                    skip = el.InnerText != screenName? true: false;
                }
                // 対象のツイートのみ取得
                if (skip == true)
                    continue;

                switch (cname)
                {
                    case "tweet-text js-tweet-text":
                        if (tw == null || tw.Text != el.InnerText)
                        {
                            tw = new Tweet();
                            tw.Text = el.InnerText;
                            items.Add(tw);
                        }
                        break;
                    case "tweet-actions js-actions":
                        tw.ID = el.GetAttribute("data-tweet-id");
                        break;
                    case "tweet-timestamp js-permalink":
                        tw.Permalink = el.GetAttribute("href");
                        break;
                    case  "_timestamp js-tweet-timestamp":
                        tw.Timestamp = el.GetAttribute("data-time");
                        if (el.GetAttribute("title") != "")
                        {
                            tw.TimestampText = el.GetAttribute("title");
                        }
                        break;
                }
            }
            return items;
        }
예제 #55
0
파일: Form1.cs 프로젝트: moonmile/etc
 /// <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;
 }
 public void AddDocumentShim(HtmlDocument doc)
 {
     HtmlDocument.HtmlDocumentShim addedShim = null;
     if (this.htmlDocumentShims == null)
     {
         this.htmlDocumentShims = new Dictionary<HtmlDocument, HtmlDocument.HtmlDocumentShim>();
         addedShim = new HtmlDocument.HtmlDocumentShim(doc);
         this.htmlDocumentShims[doc] = addedShim;
     }
     else if (!this.htmlDocumentShims.ContainsKey(doc))
     {
         addedShim = new HtmlDocument.HtmlDocumentShim(doc);
         this.htmlDocumentShims[doc] = addedShim;
     }
     if (addedShim != null)
     {
         this.OnShimAdded(addedShim);
     }
 }
예제 #57
0
    // 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 });
        }
    }
예제 #58
0
        public HtmlEditor(IDataFile _db, IDataFieldEvent _fe)
        {
            db             = _db;
            DataFieldEvent = _fe;
            InitializeComponent();

            InitializeWebBrowserAsEditor();

            _doc           = textWebBrowser.Document;
            _customButtons = new List <IHTMLEditorButton>();

            updateToolBarTimer.Start();
            updateToolBarTimer.Tick += updateToolBarTimer_Tick;

            this.AddToolbarItem(new BoldButton());
            this.AddToolbarItem(new ItalicButton());
            this.AddFontSelector(_webSafeFonts);
            this.AddFontSizeSelector(Enumerable.Range(1, 7));
            this.AddToolbarDivider();
            this.AddToolbarItem(new LinkButton());
            this.AddToolbarItem(new UnlinkButton());
            this.AddToolbarDivider();
            this.AddToolbarItem(new InsertLinkedImageButton());
            this.AddToolbarDivider();
            this.AddToolbarItem(new OrderedListButton());
            this.AddToolbarItem(new UnorderedListButton());
            this.AddToolbarDivider();
            this.AddToolbarItem(new ForecolorButton());
            this.AddToolbarDivider();
            this.AddToolbarItem(new JustifyLeftButton());
            this.AddToolbarItem(new JustifyCenterButton());
            this.AddToolbarItem(new JustifyRightButton());
            this.AddToolbarDivider();
            this.addButton_WebCopy();

            this.AddToolbarItem(btn_Clear);
            btn_Clear.Click += (se, ev) =>
            {
                this.Html = "";
            };
        }
예제 #59
0
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            switch (webBrowser1.Url.ToString())
            {
                case "https://www.streetaccount.com/index.aspx":
                    Login(username, password);
                    break;

                case "https://www.streetaccount.com/welcome.aspx":
                    if (streetAccountHtmlScraper.Mode.ToLower() == "events")
                        GotoEventsCalendar();
                    else if (streetAccountHtmlScraper.Mode.ToLower() == "earnings")
                        GotoEarningsCalendar();
                    break;

                case "https://www.streetaccount.com/eventscalendar.aspx":
                case "https://www.streetaccount.com/earnings.aspx":
                    doc = webBrowser1.Document;
                    streetAccountHtmlScraper.CreateOutput(doc.DomDocument.ToString());
                    break;
            }
        }
예제 #60
0
 // TODO: CAN I HAS PLONK HERE? <!-- I CAN HAS CHEEZBURGER -->
 public static string InsertComment(HtmlDocument document, string comm)
 {
     return null;
     //			// Gte head tags.
     //
     //
     //			HtmlElementCollection all = document.All.GetElementsByName("head");
     //			XmlTextReader reader = new XmlTextReader();
     //			XmlTextWriter writer = new XmlTextWriter(new );
     //
     //			// If comments exist within head tags.
     //			if ()
     //			// Check group
     //
     //
     //
     //			HtmlElement head = document.GetElementsByTagName("head")[0];
     //			HtmlElement scriptEl = document.CreateElement("script");
     //			IHTMLCommentElement comment = new HTMLCommentElementClass();
     //			IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
     //			element.text = "function sayHello() { alert('hello') }";
     //			head.AppendChild(scriptEl);
     //			webBrowser1.Document.InvokeScript("sayHello");
 }