C\#브 라 우 저 를 모 의 하고 자동 으로 작 동 하 는 인 스 턴 스 코드

본 고 는 웹 브 라 우 저 컨트롤 을 통 해 탐색 페이지 를 열 고 페이지 요 소 를 조작 하여 자동 검색 기능 을 실현 하 며 학습 공유 만 사용 할 수 있 습 니 다.부족 한 점 이 있 으 면 지적 해 주 십시오.
지식 에 관련되다
웹 브 라 우 저:WinForm 창 에서 아 날로 그 브 라 우 저 를 사용 하여 웹 페이지 를 열 고 탐색 합 니 다HtmlDocument:Html 문서 의 페이지 를 표시 합 니 다.불 러 올 때마다 새로운 페이지 입 니 다
  • GetElement ById(string id):ID 나 Name 을 통 해 Html 의 요 소 를 가 져 옵 니 다
  • HtmlElement:Html 태그 요 소 를 표시 합 니 다4.567917.BackgroundWorker 배경 에서 독립 적 인 작업 을 수행 하 는 프로 세 스 입 니 다.
    디자인 아이디어
    주로 비동기 대기 방식 을 사용 하여 페이지 로 딩 이 완료 되 기 를 기다 리 고 절 차 는 다음 과 같 습 니 다.

    예제 효과 도
    다음 과 같이 불 러 오기 완료 후[천안문]을 자동 으로 입력 하고 검색 을 클릭 합 니 다.

    핵심 코드
    새 페이지 를 불 러 옵 니 다.다음 과 같 습 니 다.
    
    string url = "https://www.so.com/";
     this.wb01.ScriptErrorsSuppressed = true;
     this.wb01.Navigate(url);
    주의:this.wb01.ScriptErrorsSuppressed=true;이상 스 크 립 트 코드 오류 상자 팝 업 여부 에 사용
    원 소 를 가 져 오고 값 을 부여 합 니 다.다음 과 같 습 니 다.
    
    string search_id = "input";
    string search_value = "   ";
    string btn_id = "search-button";
    HtmlDocument doc = this.wb01.Document;
    HtmlElement search = doc.GetElementById(search_id);
    search.SetAttribute("value", search_value);
    HtmlElement btn = doc.GetElementById(btn_id);
    btn.InvokeMember("click");
    예제 전체 코드 는 다음 과 같다.
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace DemoExplorer
    {
     public partial class FrmExplorer : Form
     {
      private bool isLoadOk = false;
    
      private BackgroundWorker bgWork;
    
      public FrmExplorer()
      {
       InitializeComponent();
      }
    
      private void FrmExplorer_Load(object sender, EventArgs e)
      {
       bgWork = new BackgroundWorker();
       bgWork.DoWork += bgWork_DoWork;
       bgWork.RunWorkerCompleted += bgWork_RunWorkerCompleted;
       string url = "https://www.so.com/";
       this.wb01.ScriptErrorsSuppressed = true;
       this.wb01.Navigate(url);
       bgWork.RunWorkerAsync();
      }
    
      private void bgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
       string search_id = "input";
       string search_value = "   ";
       string btn_id = "search-button";
       HtmlDocument doc = this.wb01.Document;
       HtmlElement search = doc.GetElementById(search_id);
       search.SetAttribute("value", search_value);
       HtmlElement btn = doc.GetElementById(btn_id);
       btn.InvokeMember("click");
      }
    
      private void bgWork_DoWork(object sender, DoWorkEventArgs e)
      {
       compWait();
      }
    
      private void compWait()
      {
       while (!isLoadOk)
       {
        Thread.Sleep(500);
       }
      }
    
      private void wb01_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
      {
       this.wb01.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);
       if (this.wb01.ReadyState == WebBrowserReadyState.Complete)
       {
        isLoadOk = true;
       }
       else
       {
        isLoadOk = false;
       }
      }
    
      private void Window_Error(object sender, HtmlElementErrorEventArgs e)
      {
       e.Handled = true;
      }
     }
    }
    또 다른 실현 방식(MSHTML)
    MSHTML 이란 무엇 입 니까?
    MSHTML 은 windows 가 제공 하 는 IE 브 라 우 저 를 조작 하 는 COM 구성 요소 입 니 다.이 구성 요 소 는 HTML 언어 에 있 는 모든 요소 와 속성 을 봉인 하고 표준 인 터 페 이 스 를 통 해 지정 한 웹 페이지 의 모든 요 소 를 방문 할 수 있 습 니 다.
    지식 에 관련되다
    Internet Explorer 브 라 우 저 대상 인터페이스,그 중 DocumentComplete 는 문서 로 딩 완료 이벤트 입 니 다.
    HTML DocumentClass Html 문서 대상 클래스 는 페이지 요 소 를 가 져 오 는 데 사 용 됩 니 다.
    IHTMLElement 는 페이지 요 소 를 가 져 오고 setAttribute 를 통 해 속성 값 을 설정 하 며 click()과 이 벤트 를 촉발 합 니 다.
    예제 핵심 코드
    다음 과 같다.
    
    namespace AutoGas
    {
     public class Program
     {
      private static bool isLoad = false;
    
      public static void Main(string[] args)
      {
       string logUrl = ConfigurationManager.AppSettings["logUrl"]; //  Url
       string uid = ConfigurationManager.AppSettings["uid"];//   ID
       string pid = ConfigurationManager.AppSettings["pid"];//  ID
       string btnid = ConfigurationManager.AppSettings["btnid"];//  ID
       string uvalue = ConfigurationManager.AppSettings["uvalue"];//   
       string pvalue = ConfigurationManager.AppSettings["pvalue"];//  
       InternetExplorer ie = new InternetExplorerClass();
       ie.DocumentComplete += Ie_DocumentComplete;
       object c = null;
       ie.Visible = true;
       ie.Navigate(logUrl, ref c, ref c, ref c, ref c);
       ie.FullScreen = true;
    
       compWait();
       try
       {
        HTMLDocumentClass doc = (HTMLDocumentClass)ie.Document;
        IHTMLElement username = doc.getElementById(uid);
        IHTMLElement password = doc.getElementById(pid);
        IHTMLElement btn = doc.getElementById(btnid);
        //   session,     ,         
        if (username != null && password != null && btn != null)
        {
         username.setAttribute("value", uvalue);
         password.setAttribute("value", pvalue);
         btn.click();
        }
       }
       catch (Exception ex) {
    
       }
      }
    
      public static void compWait() {
       while (!isLoad)
       {
        Thread.Sleep(200);
       }
      }
    
      /// <summary>
      ///
      /// </summary>
      /// <param name="pDisp"></param>
      /// <param name="URL"></param>
      private static void Ie_DocumentComplete(object pDisp, ref object URL)
      {
       isLoad = true;
      }
     }
    }
    이상 은 C\#아 날로 그 브 라 우 저 와 자동 으로 작 동 하 는 인 스 턴 스 코드 에 대한 상세 한 내용 입 니 다.C\#아 날로 그 브 라 우 저 와 자동 으로 작 동 하 는 자 료 는 다른 관련 글 을 주목 하 십시오!

    좋은 웹페이지 즐겨찾기