2013-10-08 3 views
2

WebBrowser Control이 webBrowser1.DocumentText을 설정할 때 HTML 태그 내에 속성을 재 배열 할 것으로 보인다 속성. 내 문제는 단순히 RichTextBoxControl (txt_htmlBody) 및 WebBrowser 컨트롤 (webBrowser1)을 Windows 폼에 추가하여 볼 수 있습니다.웹 브라우저 컨트롤 변경하기 내가 놓친 거지 모드 또는 문서 인코딩을 렌더링의 어떤 종류가 있는지</p> <p>내가 궁금하네요 ..

webBrowser1 WebBrowser 컨트롤을 추가하고 이벤트 처리기를 추가하십시오. webBrowser1_DocumentCompleted

마우스 클릭 이벤트를 웹 브라우저 컨트롤에 추가하는 데 사용되었습니다.

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
    { 
     // Attach an event to handle mouse clicks on the web browser 
     this.webBrowser1.Document.Body.MouseDown += new HtmlElementEventHandler(Body_MouseDown); 
    } 

마우스 클릭 이벤트에서 클릭 한 요소를 얻습니다.

private void Body_MouseDown(Object sender, HtmlElementEventArgs e) 
    { 
     // Get the clicked HTML element 
     HtmlElement elem = webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition); 

     if (elem != null) 
     { 
      highLightElement(elem); 

     } 
    } 

    private void highLightElement(HtmlElement elem) 
    { 

     int len = this.txt_htmlBody.TextLength; 
     int index = 0; 

     string textToSearch = this.txt_htmlBody.Text.ToLower(); // convert everything in the text box to lower so we know we dont have a case sensitive issues 
     string textToFind = elem.OuterHtml.ToLower(); 
     int lastIndex = textToSearch.LastIndexOf(textToFind); 
     // We cant find the text, because webbrowser control has re-arranged attributes in the <img> tag 
     // Whats rendered by web browser: "<img border=0 alt=\"\" src=\"images/promo-green2_01_04.jpg\" width=393 height=30>" 
     // What was passed to web browser from textbox: <img src="images/PROMO-GREEN2_01_04.jpg" width="393" height="30" border="0" alt=""/> 
     // As you can see, I will never be able to find my data in the source because the webBrowser has changed it 

    } 

폼에 txt_htmlBody RichTextBox 추가 한 변경된 RichTextBox (txt_htmlBody) 텍스트로 WebBrowser1.DocumentText을 설정 RichTextBox 이벤트의 세트의 TextChanged.
private void txt_htmlBody_TextChanged(object sender, EventArgs e) 
    { 
     try 
     { 

      webBrowser1.DocumentText = txt_htmlBody.Text.Replace("\n", String.Empty); 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

당신이 당신의 프로그램을 실행

는 txt_htmlBody에 아래 예제 HTML을 복사, 오른쪽 및 디버그 highLightElement의 이미지를 클릭합니다. WebBrowser 컨트롤이 특성을 재 배열하기 때문에 내 검색 문자열에서 지정된 텍스트를 찾을 수없는 이유를 내 의견으로 보게됩니다.

<img src="images/PROMO-GREEN2_01_04.jpg" width="393" height="30" border="0" alt=""/> 

사람이-그대로 웹 브라우저 컨트롤 내 HTML을 렌더링하는 방법을 알고 있나요?

감사합니다.

답변

1

element.OuterHtml을 통해 다시 얻은 원본 HTML과 처리 된 HTML이 1 : 1이 될 것으로 예상 할 수 없습니다. 렌더링 모드에 관계없이 거의 동일하지 않습니다.

그러나 속성이 재 배열되었지만 그 이름과 값은 여전히 ​​동일하므로 DOM을 세 번 걷거나 단순히 HtmlDocument.All을 통해 요소를 열거하고 검사 논리를 향상시켜야합니다. 그들의 속성은 HtmlElement.GetAttribute을 통해).

+1

검색 로직을 향상시키는 데 성공했습니다. 감사합니다. :) – clamchoda