【问题标题】:Getting src attribute from img tag从 img 标签获取 src 属性
【发布时间】:2024-04-29 07:45:02
【问题描述】:

我正在使用 HAP 库来解析 HTML:http://html-agility-pack.net

我基本上只想从所有img 标签中检索src 值。

我尝试了几件事,但我似乎做不到!

【问题讨论】:

    标签: c# asp.net html-agility-pack


    【解决方案1】:

    从示例页面修改:

    HtmlDocument doc = new HtmlDocument();
    doc.Load("file.htm"); //or whatever HTML file you have
    HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes("//img[@src]");
    if (imgs == null)
       return;
    foreach (HtmlNode img in imgs)
    {
       if (img.Attributes["src"] == null)
          continue;
       HtmlAttribute src = img.Attributes["src"];
       //Do something with src.Value
    }
    

    【讨论】:

    • @alexn 谢谢,我猜这就是我复制粘贴太快时的猜测:)
    • 我之前尝试过,但没有成功:无法将索引应用于“HtmlAgilityPack.HtmlNode”类型的表达式
    • @raklos 添加了一个可以解决您的问题的编辑(来自*.com/questions/1517804/…
    • @raklos 新编辑的代码对您有用吗?还是您还有问题?
    【解决方案2】:

    你有没有尝试过这样的事情:

    HtmlNodeCollection images = doc.DocumentNode.SelectNodes("//img[@src]");
    

    【讨论】: