简体   繁体   English

从网页中提取字符串

[英]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. 我需要有一个标签,该标签的文本来自网页,但为了使其无法工作,在我看来webpae返回了null,但位置正确。

    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. 该值为null,因为在您尝试访问它时尚未加载。 You should be handling it asynchronously. 您应该异步处理它。

Handle the DocumentCompleted event and access the Document in the handler. 处理DocumentCompleted事件并在处理程序中访问Document

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 :) 但这是另一种讨论:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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