【问题标题】:Xpath get image source attributeXpath获取图片源属性
【发布时间】:2015-05-23 20:00:56
【问题描述】:

如何从照片中获取所选图像的 src 属性?我真的什么都试过了。我正在使用相同的方法获取其他元素,但它不适用于此图像。这是我的代码:

div.SelectSingleNode(".//div[@class='entry-content']/p[1]/a/img").Attributes["src"].Value; 

这是上一个类“entry-header”的代码,运行良好:

div.SelectSingleNode(".//header[@class='entry-header']/div/a").Attributes["href"].Value;

我正在使用 HtmlAgilityPack,这是我的 foreach 语句:

           foreach (var div in htmlDocument.DocumentNode.SelectNodes("//article[starts-with(@class, 'post')]"))
            {
                Blog blog = new Blog();
                blog.Title= div.SelectSingleNode(".//header[@class='entry-header']/h1/a/text()").InnerText.Trim();

                //blog.Image= div.SelectSingleNode(".//div[@class='entry-content']/p[1]/a/img").Attributes["src"].Value; 
                list.Add(blog);
            }

【问题讨论】:

  • 图像元素实际上是否在您尝试遍历的工作源中?可能是动态的,entry-content 是通过 JavaScript 注入的?
  • 是的,它在 内部,就像之前的元素一样。图片来自博客文章(标题页),所以我猜它不是动态的。

标签: c# image xpath src


【解决方案1】:

试试这个。首先利用一点扩展方法:

public static HtmlNode GetFirstByClass(this HtmlNode node, string name)
{
    return node
        .Descendants()
        .FirstOrDefault(x => x.GetAttributeValue("class", null) == name);
}

像这样使用它:

var img = htmlDocument.DocumentNode.GetFirstByClass("alignnone wp-image-3195 size-full");
var src = img.GetAttributeValue("src", null);

【讨论】:

  • 这行不通,因为有更多的图像,每个都有不同的类标签,所以这只会得到第一张图像。
  • 那你为什么不写呢?您写了“如何从照片中获取所选图像的 src 属性”。你在浪费我们的时间。顺便说一句 - 很容易将此代码转换为您需要的任何内容,只要想一想。
  • @Matthew “如果你没有时间,你不需要回答我的问题,没有人告诉你必须这样做” - 请尊重他人。
  • @Matthew 另外,我认为 Randolph 的回答没有问题,即使它不完全符合您新提到的要求。 Any answer that gets the asker going in the right direction is helpful
  • @MickyDuncan 我是,这个答案很有帮助,我只是自己解释得不好......所以我没有浪费任何人的时间,或者如果我这样做不是故意的......人们有时在互联网上很粗鲁。无论如何..我很感谢你的回答:)
猜你喜欢
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多