gpt4 book ai didi

c# - WebBrowser 控件更改属性

转载 作者:太空宇宙 更新时间:2023-11-03 13:34:10 25 4
gpt4 key购买 nike

WebBrowser Control 似乎在设置 webBrowser1.DocumentText 时重新排列 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_htmlBodyRichTextBox,并设置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 中,然后单击右侧的图像并调试 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 3 或通过 HtmlDocument.All 和简单地枚举元素通过 HtmlElement.GetAttribute 检查它们的属性)。

关于c# - WebBrowser 控件更改属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19254839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com