简体   繁体   中英

Extract a string from a webpage

i need to have a label where its text comes from a web page, but for somting it doesnt work out, it appearce to me that the webpae returned null, but the location is correct.

    WebBrowser JOJO = new WebBrowser();
string Tesla = "";
                        JOJO.Url = new Uri("https://finance.yahoo.com/quote/TSLA?p=TSLA");
                        var sal = JOJO.Document.GetElementsByTagName("div");// this return null
                        foreach (HtmlElement link in sal)
                        {
    if (link.GetAttribute("className") == "D(ib) Mend(20px)")/*this is the class of the element*/        

          {
                            Tesla = link.FirstChild.InnerHtml;
                        }
                    }
                    label11.Text = Tesla;

this is the code that i have done so far, can someone see why dosnt work?

Thanks.

It is null because it didn't load yet when you try to access it. You should be handling it asynchronously.

Handle the DocumentCompleted event and access the Document in the handler.

Replace the code you have with:

WebBrowser JOJO = new WebBrowser();
JOJO.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler
                          (this.BrowserDocumentCompleted);
JOJO.Url = new Uri("https://finance.yahoo.com/quote/TSLA?p=TSLA");

And here is the handler:

void BrowserDocumentCompleted(object sender,
    WebBrowserDocumentCompletedEventArgs e)
    {
        if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
            return;

        string Tesla = "";
        var sal = (sender as WebBrowser).Document.GetElementsByTagName("div");
        foreach (HtmlElement link in sal)
        {
            if (link.GetAttribute("className") == "D(ib) Mend(20px)")
            {
                Tesla = link.FirstChild.InnerHtml;
            }
        }
        label1.Text = Tesla;
    }

Now you will maybe face other problems with redirections. But that is another discussion :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM