C#HTMLAgilityPack获取src。 xpath无效

时间:2016-12-17 18:16:10

标签: c# xpath html-agility-pack

我无法使xpath正确。我试图获取任何IMDB电影的图像,但它似乎不起作用。这是我的代码。

 // Getting the node
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//*[@id=\"title - overview - widget\"]/div[2]/div[3]/div[1]/a/img");

            // Getting the attribute data
            HtmlAttributeCollection attr = node.Attributes;

该属性为null。每次都是。 xpath不起作用,我不知道为什么。对我来说似乎很好。

1 个答案:

答案 0 :(得分:1)

您可以使用更简单的xpath

var url = "http://www.imdb.com/title/tt0816692/";
using (var client = new HttpClient())
{
    var html = await client.GetStringAsync(url);
    var doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(html);

    var img = doc.DocumentNode.SelectSingleNode("//img[@title='Trailer']")
              ?.Attributes["src"]?.Value;
    //or
    var poster = doc.DocumentNode.SelectSingleNode("//div[@class='poster']//img")
                 ?.Attributes["src"]?.Value;
}