[英]Extract a string from a webpage
我需要有一個標簽,該標簽的文本來自網頁,但為了使其無法工作,在我看來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;
這是我到目前為止所做的代碼,有人可以看到為什么不起作用嗎?
謝謝。
該值為null,因為在您嘗試訪問它時尚未加載。 您應該異步處理它。
處理DocumentCompleted事件並在處理程序中訪問Document
。
將您的代碼替換為:
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");
這是處理程序:
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;
}
現在,您可能還會面臨重定向的其他問題。 但這是另一種討論:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.