获取webBrowser的完整源代码

时间:2017-07-22 13:09:23

标签: c#

我有一个webBrowser:

webBrowser1.DocumentText = @"<html lang='en'>
<head>
<meta charset='utf-8'>
<title></title>
<style type='text/css'>
    .red
    {
        color: red;
    }
</style>
</head>
<body>
   <div class='red'>red text</div>
   sad adad a das
</body></html>";

我想获得webBrowser的完整资源:

textBox1.Text = webBrowser1.DocumentText;

但结果只是:

<HTML></HTML>

如果我在设置textBox1.text:

之前在MessageBox中显示它
MessageBox.Show(webBrowser1.DocumentText);

这很奇怪。我怎样才能获得完整的资源?

2 个答案:

答案 0 :(得分:0)

这是从WebBrowser控件

中的字符串显示HTML的正确方法
var html = @"<html lang='en'>
    <head>
    <meta charset='utf-8'>
    <title></title>
    <style type='text/css'>
        .red
        {
            color: red;
        }
    </style>
    </head>
    <body>
       <div class='red'>red text</div>
       sad adad a das
    </body></html>";

webBrowser1.DocumentText = "0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(html);
webBrowser1.Refresh();

// Will return html you provided
textBox1.Text = webBrowser1.DocumentText;

答案 1 :(得分:0)

直接回答您的初步问题,无论如何都能获得全部资料:

WebBrowser1.Document.GetElementsByTagName("HTML").Item[0].OuterHtml;
养成使用它而不是DocumentText的习惯,因为如果你在设置后对DocumentText进行任何更改,例如,更改标签的InnerHTML,那些更改将不会保存到DocumentText。

我只是将一个TextBox打到我的一个WinForms上,并将文本更新为上面的代码,它显示我的所有HTML没有问题。以下是我填写WebBrowser的示例,以防您的代码中出现拼写错误或其他内容:

WebBrowser1.Navigate("about:blank");
WebBrowser1.Document.OpenNew(false);
WebBrowser1.Document.Write("<html><head><title></title></head><body></body></html>");

我从没有直接写过DocumentText的运气。这种方法没有问题。

相关问题