2015-09-04 77 views
0

我的代碼C#獲取一個HTML元素

<button value="1" class="_42ft _4jy0 _n6m _4jy3 _517h _51sy" data-hover="tooltip" aria-label="Start a video call with Tsiato" type="submit" id="js_rk"><i class="_e0b img sp_qk8sNUxukfD sx_4816f8"></i></button> 

,我試圖訪問「詠歎調標籤」,看它是否包含單詞「開始」這個塊的屬性...

使用此代碼

try 
{ 
    HtmlElementCollection buttons = pinger.Document.GetElementsByTagName("button"); 
    foreach (HtmlElement curElement in buttons) 
    { 
     if (curElement.GetAttribute("classname").ToString() == "_42ft _4jy0 _n6m _4jy3 _517h _51sy") 
     { 
      if (curElement.GetAttribute("aria-label").ToString().Contains("Start a video call")) 
      { 
       label5.Text = "online"; 
      } 
     } 
    } 
} catch (NullReferenceException b) 
{ 
    Console.WriteLine(b.ToString()); 
} 

我可以找到類,但我不能得到屬性「詠歎調標籤」,看它是否包含任何「開始」的文字... 你能告訴我什麼這裏錯了嗎? :\

+0

你得到了什麼錯誤? –

+0

Nullreferenceexception –

+0

如果在某處使用DOM對象,可能需要使用'ariaLabel'?只是一個猜測。 – Alex

回答

0

因此,如果有一個按鈕不包含aria-label作爲屬性,您將得到nullreference異常,因爲您在null上使用Contains()方法。

那麼試試這個:

 String ariaLabel = curElement.GetAttribute("aria-label"); 
     if (ariaLabel != null && ariaLabel.Length != 0) 
     { 
      if(ariaLabel.Contains("Start a video call")) 
      { 
       // do your stuff 
      } 
     } 
0

你可以試試這個 -

var p = "<button value='1' class='_42ft _4jy0 _n6m _4jy3 _517h _51sy' data-hover='tooltip' aria-label='Start a video call with Tsiato' type='submit' id='js_rk'><i class='_e0b img sp_qk8sNUxukfD sx_4816f8'></i></button>"; 
var k = new XmlDocument(); 
k.Load(new MemoryStream(Encoding.UTF8.GetBytes(p.ToCharArray()))); 
Console.WriteLine(k.GetElementsByTagName("button")[0].Attributes["aria-label"].Value); 
0
  1. 類=屬性有名稱爲 「類」,而不是 「類名」。
  2. 如果你的方法GetAttribute(string)可以返回null,你應該總是檢查返回的值。

    if (curElement.GetAttribute("classname") == "_42ft _4jy0 _n6m _4jy3 _517h _51sy" 
    && (curElement.GetAttribute("aria-label") ?? "").Contains("Start a video call")) 
    { 
        label5.Text = "online"; 
    }