C\#브 라 우 저 를 모 의 하고 자동 으로 작 동 하 는 인 스 턴 스 코드
지식 에 관련되다
웹 브 라 우 저:WinForm 창 에서 아 날로 그 브 라 우 저 를 사용 하여 웹 페이지 를 열 고 탐색 합 니 다HtmlDocument:Html 문서 의 페이지 를 표시 합 니 다.불 러 올 때마다 새로운 페이지 입 니 다
디자인 아이디어
주로 비동기 대기 방식 을 사용 하여 페이지 로 딩 이 완료 되 기 를 기다 리 고 절 차 는 다음 과 같 습 니 다.
예제 효과 도
다음 과 같이 불 러 오기 완료 후[천안문]을 자동 으로 입력 하고 검색 을 클릭 합 니 다.
핵심 코드
새 페이지 를 불 러 옵 니 다.다음 과 같 습 니 다.
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\#아 날로 그 브 라 우 저 와 자동 으로 작 동 하 는 자 료 는 다른 관련 글 을 주목 하 십시오!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
C#Task를 사용하여 비동기식 작업을 수행하는 방법라인이 완성된 후에 이 라인을 다시 시작할 수 없습니다.반대로 조인(Join)만 결합할 수 있습니다 (프로세스가 현재 라인을 막습니다). 임무는 조합할 수 있는 것이다. 연장을 사용하여 그것들을 한데 연결시키는 것이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.