I'm trying to get the src property from an img
tag.
The problem's that I get no src
of the image, but an empty string. Instead if I remove the //img/@src
I see the content of a
tag (image). What's the problem?
I saw other similar question, but no solution provided working for me.
<div class="clearfix">
<div class="container left">
<div class="logo">
<a href="/teams/japan/japan/1348/">
<img src="http://cache.images.core.optasports.com/soccer/teams/150x150/1348.png" alt="Giappone">
</a>
</div>
</div>
this is my code:
var shieldHomeContainer = nodeCollection.SelectSingleNode("//div[@class='container left']//div[@class='logo']//a//img/@src");
try something like this
var shieldHomeContainer = nodeCollection.SelectSingleNode("//img").Attributes["src"].Value;
You can't select an attribute directly. You need to select an element and then call GetAttributeValue()
.
var h=new HtmlAgilityPack.HtmlDocument();
h.LoadHtml(@"
<div class=""clearfix"">
<div class=""container left"">
<div class=""logo"">
<a href = ""/teams/japan/japan/1348/"" >
<img src=""something"" alt=""Giappone"">
</a>
</div>
</div>");
var img = h.DocumentNode.SelectSingleNode(
"//div[@class='container left']//div[@class='logo']//a//img");
Debug.WriteLine(img.GetAttributeValue("src","nothing"));
If you want to make sure that the element has that attribute, use img[@src]
.