pictureBox.ImageLocation可以';无法检索HTMLElement

本文关键字:检索 HTMLElement ImageLocation 可以 pictureBox | 更新日期: 2023-09-27 17:58:40

我正试图从网站上获取一个图片元素,并将其显示在PictureBox中。。该代码不会返回任何错误,但不会显示任何内容。

我正在使用WebBrowser类,并尝试使用一个事件来显示元素,该事件在网页加载后调用

                void wb_DocumentCompleted(object sender,       WebBrowserDocumentCompletedEventArgs e)
    {
        pictureBox1.ImageLocation = wb.Document.GetElementById("ctl00_mainContent_identityBar_emblemImg").InnerText; // does nothing       
        label1.Text = "Last Played: " + wb.Document.GetElementById("ctl00_mainContent_lastPlayedLabel").InnerText; // works fine
    }

以下是我试图从中提取图像的网页示例:http://halo.bungie.net/Stats/Halo3/Default.aspx?player=SmitherdxA27^这个例子中是一只橙色背景的鸟。

pictureBox.ImageLocation可以';无法检索HTMLElement

非常简单:

private void Form1_Load(System.Object sender, System.EventArgs e)
{
    webBrowser1.Navigate("http://halo.bungie.net/Stats/Halo3/Default.aspx?player=SmitherdxA27");
}
private void WebBrowser1_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
    if ((e.Url.ToString() == "http://halo.bungie.net/Stats/Halo3/Default.aspx?player=SmitherdxA27"))
    {
        HtmlElement elem = webBrowser1.Document.GetElementById("ctl00_mainContent_identityStrip_EmblemCtrl_imgEmblem");
        string src = elem.GetAttribute("src");
        this.pictureBox1.ImageLocation = src;
    }
}

祝你好运!

它不返回任何内容,因为图像标记不包含内部文本。您需要使用元素并生成位图。

public Bitmap GetImage(string id)
    {
        HtmlElement e = webBrowser1.Document.GetElementById(id);
        IHTMLImgElement img = (IHTMLImgElement)e.DomElement;
        IHTMLElementRenderFixed render = (IHTMLElementRenderFixed)img;
        Bitmap bmp = new Bitmap(e.OffsetRectangle.Width, e.OffsetRectangle.Height);
        Graphics g = Graphics.FromImage(bmp);
        IntPtr hdc = g.GetHdc();
        render.DrawToDC(hdc);
        g.ReleaseHdc(hdc);
        return bmp;
    }