HTML源代码如下
<img id="itemImage" src="https://www.xyz.com/item1.jpg">
我使用以下LINQ查询来获取SRC值(图像链接)
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)
以获取单个元素,然后再将其转换为字符串。
.Select(node => node.Attributes["src"].Value).First().ToString();
此外,如果有可能不存在所需元素,则FirstOrDefault()
和SingleOrDefault()
将返回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();