如何获取当前页面的HTML?

4
我想解析当前页面的HTML。在ASP.NET中,我该如何获取当前页面的HTML? 提前感谢。
3个回答

7

客户端

在Internet Explorer中:

右键单击浏览器 --> 查看源代码

在Firefox中:

右键单击浏览器 --> 查看页面源代码

服务器端

您可以覆盖页面的渲染方法来捕获服务器端的HTML源代码。

protected override void Render(HtmlTextWriter writer)
{
    // setup a TextWriter to capture the markup
    TextWriter tw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(tw);

    // render the markup into our surrogate TextWriter
    base.Render(htw);

    // get the captured markup as a string
    string pageSource = tw.ToString();

    // render the markup into the output stream verbatim
    writer.Write(pageSource);

    // remove the viewstate field from the captured markup
    string viewStateRemoved = Regex.Replace(pageSource,
        "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*?\" />",
        "", RegexOptions.IgnoreCase);

    // the page source, without the viewstate field, is in viewStateRemoved
    // do what you like with it
}

你错过了服务器-客户端之间的HttpRequest和HttpResponse。 - cjk
included in the second run :) - solairaja

2

重写Render方法并使用自己的HtmlWriter调用base.Render。


有没有一种方法可以使用Request.Url获取当前页面的HTML? - Constantine

1
你真的想解析HTML吗?这是一个棘手的问题。如果你不是非常必须这样做,我建议你使用客户端DOM方法来避免它(如果可以接受客户端解决方案的话)。如果你需要大量解析HTML,你可以考虑使用jQueryPrototype或其他一些工具来帮助你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接