[英]WebBrowser Control Changing Attributes
设置webBrowser1.DocumentText。时, WebBrowser Control
似乎在HTML标记中重新排列属性。
我想知道是否缺少某种渲染模式或文档编码。 只需将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_htmlBody
RichTextBox
添加到窗体,并设置RichTextBox
事件的TextChanged以将WebBrowser1.DocumentText
设置为RichTextBox
(txt_htmlBody)文本已更改。
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中,然后单击右侧的Image并调试highLightElement。 通过我的评论,您将看到为什么无法在搜索字符串中找到指定的文本,因为WebBrowser
控件会重新排列属性。
<img src="images/PROMO-GREEN2_01_04.jpg" width="393" height="30" border="0" alt=""/>
有谁知道如何使WebBrowser控件按原样呈现我的HTML?
感谢您的时间。
当您通过element.OuterHtml
获得处理后的HTML时,您不能期望它与原始源的1:1相同。 不论渲染模式如何,它几乎永远不会相同。
但是,尽管属性可能已经重新排列,但是它们的名称和值仍然相同,因此您只需要改善搜索逻辑(例如,通过遍历DOM三种或通过HtmlDocument.All枚举元素并检查其属性)即可。通过HtmlElement.GetAttribute )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.