【问题标题】:How can I find a specific div by name in an HTMLDocument?如何在 HTMLDocument 中按名称查找特定 div?
【发布时间】:2018-04-27 22:31:01
【问题描述】:

我真的很难浏览HTMLDocument 类中的所有属性。我有一个网页正在加载到嵌入在 Window 中的 WPF WebBrowser 中。我有一个类似的活动

    private void _browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        HTMLDocument document = (HTMLDocument) this._browser.Document;
        if (document.body != null)
        {
            this.Height = //get the div with the id 'wrapper' and get it's height
        }
    }

基本上。当页面完成导航后,我想获取 HTML 中特定分隔线的高度。

下面是 HTML 的样子:

<html lang="en-US">
    <head>…</head>
    <div id = "wrapper">…</div>
    <body blah blah blah>…</body>
</html>

我似乎找不到这个 HTML,虽然它在 HTMLDocument 类中。我想获取此分隔线的高度并将窗口高度设置为此分隔线的高度加上按钮和其他所需的其他空间。

我应该在哪里搜索?

一开始我在尝试

HTMLDocument document = (HTMLDocument) this._browser.Document;
this.Height= document.body.offsetHeight

但这远非正确,而且我似乎找不到任何我读过的HTMLElement 类型的东西,您可以在其中访问个人HTMLElements。

如果您以前使用过这个课程或者可以看到我哪里出错了,我们将不胜感激。

【问题讨论】:

    标签: c# html wpf mshtml dom


    【解决方案1】:

    请下载HTML Agility Pack并将其添加到项目参考中

    protected void BtnIndex_Click(object sender, EventArgs e)
    {
        string source = getHtml("http://stackoverflow.com");
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(source);
        HtmlNodeCollection cont;
        cont = doc.DocumentNode.SelectNodes("//div[@id='wrapper']");
    }
    
    string getHtml(string url)
    {
        string Shtml = string.Empty; ;
        try
        {
            //WebClient client = new WebClient();
            //client.Encoding = Encoding.UTF8;
            //Shtml = client.DownloadString(url);
            //Shtml = new WebClient().DownloadString(url); bejoz utf-8
    
            HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    
            myWebRequest.Method = "GET";
    
            // Make request for web page
            HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
    
            StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
    
    
            Shtml = myWebSource.ReadToEnd();
            myWebResponse.Close();
        }
        catch
        {
            Response.Write(" error: " + url + Environment.NewLine);
        }
        return Shtml;
    }
    

    【讨论】:

    • 这似乎是一个了不起的工具,但是有没有办法从 mshtml HTMLDocument 类访问节点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2012-04-15
    相关资源
    最近更新 更多