HTML Source는 다음과 같습니다.
<img id="itemImage" src="https://www.xyz.com/item1.jpg">
SRC 값을 얻으려면 다음 LINQ 쿼리를 사용하고 있습니다 (이미지 링크)
string imageURL = document.DocumentNode.Descendants("img")
.Where(node => node.Attributes["id"] != null && node.Attributes["id"].Value == "itemImage")
.Select(node => node.Attributes["src"].Value).ToString();
그러나 imageURL은 다음과 같이 출력을 제공합니다.
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[HtmlAgilityPack.HtmlNode,System.String]
문제는 그것을 문자열로 변환하는 것입니다. Select()
는 기본적으로 열거자를 문자열로 변환하기 위해 IEnumerable<T>
반환합니다 (오류 메시지가 말하는 것처럼). 단일 요소를 문자열로 보내기 전에 First()
또는 Single()
또는 Take(1)
를 호출 Take(1)
.
.Select(node => node.Attributes["src"].Value).First().ToString();
또한 원하는 요소가 없을 가능성이있는 경우 FirstOrDefault()
및 SingleOrDefault()
는 예외를 throw하는 대신 null을 반환합니다. 이 경우 나는
var imageUlr = ... .Select(node => node.Attributes["src"].Value).FirstOrDefault();
if (imageUrl != null)
{
// cast it to string and do something with it
}
.DefaultIfEmpty (string.Empty) .FirstOrDefault를 추가하십시오.
string imageURL = document.DocumentNode.Descendants("img")
.Where(node => node.Attributes["id"] != null && node.Attributes["id"].Value == "itemImage")
.Select(node => node.Attributes["src"].Value)
.DefaultIfEmpty(string.Empty)
.FirstOrDefault()
.ToString();