我正在嘗試使用Html Agility Pack和LINQ從HTML表中獲取所有單元格。我已經在HtmlAgilityPack.HtmlDocument中加載了HTML源代碼,並使用LINQ選擇了代碼。但是在使用foreach迭代結果後,它會在第二個記錄中崩潰。
這是HTML源代碼的一個片段:
<tr>
<td class='city'>New York</td>
<td>Card 1</td>
</tr>
<tr>
<td class='city'>London</td>
<td>Card 2</td>
</tr>
<tr>
<td class='city'>Tokyo</td>
<td>Card 3</td>
</tr>
<tr>
<td class='city'>Berlin</td>
<td>Card 4</td>
</tr>
這就是我所做的:
htmlDoc.LoadHtml(await msgRecived.Content.ReadAsStringAsync());
var tds=
from td in htmlDoc.DocumentNode.Descendants("td")
where td.Attributes["class"].Value == "city"
select td.InnerText;
foreach (var td in tds)
{
citiesText = citiesText + " " + td;
}
它只返回第一個元素,例如,如果不使用foreach,我會:
citiesText = tds.ElementAt(0);
它返回紐約 ,但是如果我嘗試使用ElementAt(1),它會在沒有設置為對象實例的Object引用時崩潰。
有幫助嗎?謝謝
您需要確保Attributes["class"]
不為null
:
var tds =
from td in doc.DocumentNode.Descendants("td")
where td.Attributes["class"] != null && td.Attributes["class"].Value == "city"
select td.InnerText;
檢索到的第二個<td>
沒有class
屬性,因此在這種情況下訪問Attributes["class"]
時,您將獲得null
。在null
上調用.Value
會導致異常。
或者,您可以使用GetAttributeValue
:
var tds =
from td in doc.DocumentNode.Descendants("td")
where td.GetAttributeValue("class", null) == "city"
select td.InnerText;