2013-10-08 41 views
2

WebBrowser Control似乎设置webBrowser1.DocumentText时重新安排HTML标签中的属性..WebBrowser控件变更属性

我不知道是否有某种渲染,我很想念模式或文档编码的。我的问题可以通过简单地将RichTextBoxControl(txt_htmlBody)和WebBrowser控件(webBrowser1)添加到Windows窗体来看到。

添加webBrowser1 WebBrowser控件,并添加一个事件处理程序; webBrowser1_DocumentCompleted

我用它将我的鼠标单击事件添加到Web浏览器控件。

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_htmlBodyRichTextBox到窗体,并设置RichTextBox事件来设置所述WebBrowser1.DocumentText作为RichTextBox(txt_htmlBody)文本改变的框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); 
     } 
    } 

当你运行你的程序,下面的示例HTML复制到txt_htmlBody,并单击右侧和调试highLightElement图像。您会在我的评论中看到为什么我无法在搜索字符串中找到指定的文本,因为WebBrowser控件会重新排列属性。

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

有谁知道如何使WebBrowser控件呈现我的HTML原样?

谢谢你的时间。

回答

1

当您通过element.OuterHtml获取它时,您不能期望处理后的HTML与原始源相同为1:1。无论渲染模式如何,它几乎都不相同。但是,尽管属性可能已重新排列,但它们的名称和值仍然相同,因此您只需改进搜索逻辑(例如,通过步行DOM 3或通过HtmlDocument.All简单列举元素并检查他们的属性通过HtmlElement.GetAttribute)。

+1

我最终改进了我的搜索逻辑,谢谢:) – clamchoda