HtmlNode Select img 其中 alt 等于值
HtmlNode Select img where alt equals value
我想要 select 图像的 src
,其中 img 的 alt
等于给定值。下面我给出了 html 我想从中提取图像:
<div class="col-md-4 cush">
<div class="col-xs-12 col-sm-6 col-lg-8">
<div class="ps4 cush">
<img src="https://website/assets/img/Anim-img/platforms/PS4-logo.png" alt=PS4 id="platformImage">
</div>
</div>
<div class="col-xs-6 col-md-4">
<img src="IMAGE_I_WANT_TO_GET" alt=The Alternative>
</div>
</div>
我尝试了以下我认为 return 正确的值:
originalDetails.CoverImage = htmlNode.SelectNodes($"//img[contains(@alt, '{What i'm trying to match}')]")
.Select(x => x.GetAttributeValue("src", ""))
.FirstOrDefault();
但是我收到一个错误 Value cannot be null. Parameter name: source
。是否有更简单的方法通过图像的 alt
是否等于给定值来获取图像的来源?
如果有人想知道我是如何获得图像源的,我做了以下操作。
// Get all the img tags in the node (two in this case)
var images = htmlNode.Descendants("img").ToArray();
// Image source
// we know that we do NOT want the first image, just the second and that the first
// attribute in that second image is the image source (what we want).
// So we get the 2nd image and the first attribute of that image
originalDetails.CoverImage = images[1].Attributes.FirstOrDefault().Value;
我知道这不是最好的方法,但它可以完成工作。
我想要 select 图像的 src
,其中 img 的 alt
等于给定值。下面我给出了 html 我想从中提取图像:
<div class="col-md-4 cush">
<div class="col-xs-12 col-sm-6 col-lg-8">
<div class="ps4 cush">
<img src="https://website/assets/img/Anim-img/platforms/PS4-logo.png" alt=PS4 id="platformImage">
</div>
</div>
<div class="col-xs-6 col-md-4">
<img src="IMAGE_I_WANT_TO_GET" alt=The Alternative>
</div>
</div>
我尝试了以下我认为 return 正确的值:
originalDetails.CoverImage = htmlNode.SelectNodes($"//img[contains(@alt, '{What i'm trying to match}')]")
.Select(x => x.GetAttributeValue("src", ""))
.FirstOrDefault();
但是我收到一个错误 Value cannot be null. Parameter name: source
。是否有更简单的方法通过图像的 alt
是否等于给定值来获取图像的来源?
如果有人想知道我是如何获得图像源的,我做了以下操作。
// Get all the img tags in the node (two in this case)
var images = htmlNode.Descendants("img").ToArray();
// Image source
// we know that we do NOT want the first image, just the second and that the first
// attribute in that second image is the image source (what we want).
// So we get the 2nd image and the first attribute of that image
originalDetails.CoverImage = images[1].Attributes.FirstOrDefault().Value;
我知道这不是最好的方法,但它可以完成工作。