DocumentNode.SelectNodes返回null - HtmlAgilityPack

时间:2017-01-05 18:21:39

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

我想获取存储在Html源代码的 span 标签中的不同电影的IMDB评级。为此,我试图使用Html解析从HTML span标签收集数据。一切正常,直到调用DocumentNode的SelectNodes()方法,返回null。

我知道这个问题之前曾被多次询问过,但是尽管做了大量研究并尝试了不同的解决方案,我似乎无法弄清楚我的代码有什么问题。为了完成我的学期项目,解决这个问题对我来说真的很重要,所以任何帮助都会受到赞赏。 感谢。

string url = "https://www.google.com/search?client=opera&q=into+the+wild&sourceid=opera&ie=UTF-8&oe=UTF-8";

        StreamReader sourceCode = makeHttpRequest(url);
        //makeRequest() returns the html source code of the url
        String sourceCodeString = sourceCode.ReadToEnd();

        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(sourceCodeString);
        var itemList = doc.DocumentNode.SelectNodes("//span[@class='_tvg']")
                .Select(p => p.InnerText)
                .ToList();

1 个答案:

答案 0 :(得分:1)

这里的关键点是设置用户代理。

下面的代码返回3个结果,如果删除User-Agent,您将获得空值...

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
    var html = await client.GetStringAsync("https://www.google.com/search?client=opera&q=into+the+wild&sourceid=opera&ie=UTF-8&oe=UTF-8");
    var doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(html);
    var result = doc.DocumentNode
                    .SelectNodes("//span[@class='_tvg']")
                    .Select(p => p.InnerText)
                    .ToList();


}