html Agility Pack 및 LINQ를 사용하여 HTML 표에서 모든 셀을 가져 오려고합니다. HTML 소스를 HtmlAgilityPack.HtmlDocument에로드하고 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)를 시도하면 오브젝트 참조가 오브젝트 인스턴스로 설정되지 않아 충돌 합니다.
어떤 도움이 필요합니까? 감사
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
속성이 <td>
경우 Attributes["class"]
에 액세스하면 null
됩니다. null
.Value
를 호출하면 예외가 발생합니다.
또는 GetAttributeValue
사용할 수도 있습니다.
var tds =
from td in doc.DocumentNode.Descendants("td")
where td.GetAttributeValue("class", null) == "city"
select td.InnerText;
그냥 추측하지만 아마도 첫 번째 요소의 td를보고있을 것입니다. 어쩌면 너는 필요할지도 모른다.
대신 htmlDoc.DocumentNode.Descendants ( "table").