【问题标题】:HtmlNode Select img where alt equals valueHtmlNode 选择 alt 等于 value 的 img
【发布时间】:2019-11-02 00:06:59
【问题描述】:

我想选择图像的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>

我尝试了以下我认为会返回正确值的方法:

        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 是否等于给定值来获取图像的来源?

【问题讨论】:

  • 您发布的 HTML 并不完全理想...Agility Pack 将尝试以某种方式解析 alt=The Alternative... 但未引用的属性,尤其是空格,没有必要解析你想要的方式......
  • 你能发布一个完整的问题示例吗?如果能编译就好了。

标签: c# html linq html-agility-pack


【解决方案1】:

对于任何想知道我如何获得图像源的人,我做了以下操作。

// 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;

我知道这不是最好的方法,但它可以完成工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多